Perl FAQ 5.9: Why don't backticks work as they do in shells?

Perl FAQ 5.9

Why don't backticks work as they do in shells?

Several reasons. One is because backticks do not interpolate within double quotes in Perl as they do in shells. Let's look at two common mistakes:

     $foo = "$bar is `wc $file`";  # WRONG

This should have been:

     $foo = "$bar is " . `wc $file`;

But you'll have an extra newline you might not expect. This does not work as expected:

$back = `pwd`; chdir($somewhere); chdir($back); # WRONG

Because backticks do not automatically eat trailing or embedded newlines. The chop() function will remove the last character from a string. This should have been:

      chop($back = `pwd`); chdir($somewhere); chdir($back);

You should also be aware that while in the shells, embedding single quotes will protect variables, in Perl, you'll need to escape the dollar signs.

    Shell: foo=`cmd 'safe $dollar'`
    Perl:  $foo=`cmd 'safe \$dollar'`;

Other resources at this site: