Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: perl -n seemingly eating a line of input

by shmem (Chancellor)
on May 01, 2017 at 11:42 UTC ( [id://1189254]=note: print w/replies, xml ) Need Help??


in reply to perl -n seemingly eating a line of input

This happens because at the time your loop code @a = <>; is run, there has already been an assignment to $_.

perl -MO=Deparse -n -e '@a = <>; END{ print @a; } ' LINE: while (defined($_ = <ARGV>)) { @a = <ARGV>; sub END { print @a; } ; }

This captures the first line also into @a:

echo -e '55\n44\n33\n22\n11\n' | perl -n -e '@a = ($_,<>); END{ print +@a; } '
perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Replies are listed 'Best First'.
Re^2: perl -n seemingly eating a line of input
by mldvx4 (Friar) on May 01, 2017 at 12:29 UTC

    Thanks. I see the problem now, though don't see the way around it. Adding the parenthesis catches the first number, but also produces an extra line that is empty.

      ...but also produces an extra line that is empty.

      That is due to your trailing \n and has nothing to do with the parenthesized $_,<> - compare

      echo -e '55\n44\n33\n22\n11\n' | perl -n -e '@a = ($_,<>); END{ print +@a; } ' echo -e '55\n44\n33\n22\n11' | perl -n -e '@a = ($_,<>); END{ print @a +; } '

      - because echo -e will add a newline to its argument, so there are two of them, and thus an empty line. Use echo -en to suppress that:

      echo -en '55\n44\n33\n22\n11\n' | perl -n -e '@a = ($_,<>); END{ print + @a; } '
      perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
      Don't use -n, or change the way you process the lines:
      echo -e '55\n44\n33\n22\n11\n' | perl -n -e 'push @a, $_; END{ print @ +a; } '

      Explanation: -n makes perl loop through the input lines, and my code puts each line in turn onto the array. After all input is processed, I print out the array.

      If you want to do -e '@a=<>;' and get all the lines, simply don't use -n.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1189254]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2024-04-19 16:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found