http://qs321.pair.com?node_id=969766


in reply to Re: sh: -c: line 1: syntax error near unexpected token `|'
in thread sh: -c: line 1: syntax error near unexpected token `|'

That's pretty much the actual code is I'm afraid. Additionally, you can think of $cmd as below:
$cmd = "------------- Hello World ------------";

Replies are listed 'Best First'.
Re^3: sh: -c: line 1: syntax error near unexpected token `|'
by lune (Pilgrim) on May 10, 2012 at 09:23 UTC
    You are using Perl, but your question pertains to the shell that evaluates the command in backticks. To solve this, you have to see, why your shell doesn't like the command.

    Besides take a look at perlop. There is a section about quoting (and you should quote, what you are giving to the shell) stating about the command given in backticks: "How that string gets evaluated is entirely subject to the command interpreter on your system."

    For example, when I try to run your code on my Ubuntu I am getting something like

    #!/usr/bin/perl use strict; use warnings; my $cmd = "------------- Hello World ------------"; my $result = `echo $cmd | grep '\-\-\-\-'`; print $result . "\n";
    grep: unknown option »----«

    I am assuming however, that you don't really want to search a string in Perl that way (there are better ways), but to learn something about calling external commands.

Re^3: sh: -c: line 1: syntax error near unexpected token `|'
by cdarke (Prior) on May 10, 2012 at 09:23 UTC
    Probably better to place quotes around the command, for example:
    $cmd = "'------------- Hello World ------------'";
    or use somthing like q()

    Also, you might like to use "end of options":
    my $result = `echo -- $cmd | grep -- '\-\-\-\-'`;

      Regarding quotes, the OP might find a module that provides shell escaping useful. Such as String::ShellQuote.

      printf is probably more surefire than echo there:

      printf "%s" "$cmd" | grep -e '----'

      But shelling out is very error-prone (as the OP discovered) and pretty vain when the code can be reproduced in Perl in a few lines.