Search code examples
perlunixcut

Why do I need list context when writing unix command output to a file in Perl?


I'm trying to output the output from a unix command to a file handle (which goes to an output file). Initially my code was like this:

open (OUT,'>',$out)|| die "cannot open $out";
my $file =`cut -f $list $in`;
print OUT $file;
close OUT;

It gave me a "segmentation fault" error message, which is pretty rare for a perl script... I searched around and make one small change below in the second and third line by changing the output into an array @file instead of variable $file and somehow, for whatever reason, it worked!

open (OUT,'>',$out)|| die "cannot open $out";
my @file =`cut -f $list $in`;
print OUT @file;
close OUT;

Does anyone understand why it worked and what is the difference between outputting into array vs a scalar?


Solution

  • qx/readpipe/backticks in scalar context will try to load the external command's output into a single scalar variable. In list context, the output is loaded into a list of several scalars.

    If the external command's output is extraordinarily long, Perl might choke on trying to cram it into a single string, but not have a problem creating several small strings and loading them to an array.