mkHun mkHun - 6 months ago 23
Perl Question

Why use the -p|-n in slurp mode in perl one liner?

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;

Answer

Without -n or -p the default $_ does not get set since there is no implicit while loop, 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 -e 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, the mere -0777 only sets $/. We can even add a read

# use warnings;
local $/;
<>; 
print;

The <> does read everything in one go but there is no default input and pattern-searching space $_ 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.)

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 , readline, readdir or each operation's result is tested by itself as the sole criterion of a while test. Outside a while test, this will not happen.

With -n or -p there is a while (<>) loop setup so $_ does get set.

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.