Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this oneliner - echo "hello" | perl -e '<>; print' does not work

Tags:

perl

I am still new to Perl and had problem to understand why this one liner does not work.

My understanding is that it read from input to $_ and then print should be able to print it out but it does not wait for input from keyboard and does not print anything.

[admin@mb125:~/src/test/scripting] : echo "hello" | perl -e '<>; print'

I know if I do print before <> it works, like following

[admin@mb125:~/src/test/scripting] : echo "hello" | perl -e 'print <>'
hello

Can anyone explain for me why first one liner does not work ?

thanks

like image 477
Ask and Learn Avatar asked Mar 10 '26 14:03

Ask and Learn


2 Answers

<> without an assignment only assigns to $_ automatically if it's used like this:

while (<>)

Since you used it outside while, this special case doesn't apply.

like image 179
Barmar Avatar answered Mar 12 '26 07:03

Barmar


Here's another one-liner that looks like it will do what you're looking for:

echo "world" | xargs perl -e 'print "Hello " . (shift @ARGV) . "\n"; '

A Perl script takes parameters from the command line and stores them in the special variable @ARGV. So if you have a Perl script that you call with "perl myscript.pl foo bar baz", @ARGV will contain ['foo','bar','baz']. You can then use array operators like shift, pop or $array[$n] to access the data.

xargs (in this case) takes the parameters piped into it and passes them on to the Perl script like they were command-line arguments. It's a pretty handy function.

Oh, and if you do this you have to have the parentheses around (shift @ARGV) . Otherwise Perl throws a "not an ARRAY reference" error when it gets to "\n", or at least mine does.

like image 33
Creede Avatar answered Mar 12 '26 06:03

Creede