In perl one liner slurp mode is 0777 I hope which is equal to below script
open my $fh, "<","file";
local $/;
my $s = <$fh>; #now whole file stored into the $s
Here we are not using any loop for storing all the elements together(single data).
But in perl one liner, Why do we use the -p|-n switch to enable the slurp mode (-0777)? What is the performance gain here.?
-p | -n using for looping purpose. So the actual performance of one liner is like the below script or anything else?
open my $fh, "<","file";
my $s;
while (<$fh>)
{
$s.=$_;
}
print $s;
Without -n or -p there is no implicit while (<>) loop so the default $_ does not get set, and the STDIN isn't read either. If we want to have <> and $_ by default in the slurp mode we need one of these switches along with -0777, which on its own merely (un)sets $/. This
echo "hello" | perl -0777 -e 'print'
prints nothing, and with -w it warns of Use of uninitialized value $_. Now this
echo "hello" | perl -0777 -e '$v = <>; print $v'
does print hello. The STDIN can be read into a variable, so 'slurp' is on.
In terms of what this is equivalent to, mere -0777 only does $/ = undef. If we add a read
# use warnings;
local $/;
<>;
print;
The <> does read everything in one go but there is no default input and pattern-searching space (variable $_)
so what is read is not assigned to anything. With the warnings on we get to hear about it. (Thanks to Jonathan Leffler for mentioning STDIN in a comment.)
The code equivalent to using -n is
while (defined($_ = <ARGV>)) { }
so we get standard input and $_ set up. Run perl -MO=Deparse -n -e 1 to see these.
In perlvar the conditions are listed for when "... Perl will assume $_ ...". The last bullet
The default place to put the next value or input record when a
<FH>,readline,readdiroreachoperation's result is tested by itself as the sole criterion of awhiletest. Outside awhiletest, this will not happen.
With -n or -p switches we get this, and all of standard input.
Note, your example is not exactly equivalent since it does assign.
Comment on specific statements in the question.
The slurp does not get "enabled" by these switches -- it is set up by the -0777 flag. We use them because we get automatic standard input and $_ with them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With