Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: sh: -c: line 1: syntax error near unexpected token `|'

by perl@1983 (Sexton)
on May 10, 2012 at 08:22 UTC ( #969766=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://969766]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2022-07-01 14:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My most frequent journeys are powered by:









    Results (99 votes). Check out past polls.

    Notices?