candlerb has asked for the wisdom of the Perl Monks concerning the following question:

Could someone explain to me why the following code depends on whether the value is assigned to a variable or not?
use CGI 'escapeHTML'; print "\n--- take 1 ---\n"; print escapeHTML(`echo abc; echo def; echo ghi`); print "\n--- take 2 ---\n"; print escapeHTML($b = `echo abc; echo def; echo ghi`); print "\n--- take 3 ---\n"; $c = `echo abc; echo def; echo ghi`; print escapeHTML($c);
When I run this, I get:
--- take 1 --- abc
 --- take 2 --- abc def ghi --- take 3 --- abc def ghi
Tested on:

Replies are listed 'Best First'.
Re: backticks/escapeHTML strange behaviour with assignment
by candlerb (Novice) on Nov 29, 2013 at 08:46 UTC
    I found it. man perlop for backticks: "In scalar context, a single string consisting of all output is returned. In list context, a list of values is returned, one per line of output." Solution:
    print escapeHTML(scalar(`echo abc; echo def; echo ghi`));
Re: backticks/escapeHTML strange behaviour with assignment
by boftx (Deacon) on Nov 29, 2013 at 08:47 UTC

    The only thing I can think of right off the top is that without the assignment in Take 1 the newlines are preventing more than the first "echo" from being seen by escapeHTML.

    It helps to remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.