perl implicit loop switch

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
<disclaimer: I'm not an expert at all in oneliners>

... yet I sometimes use them to process datafiles.

And I often find it useful to use the -n switch to extract data, one
line at a time.
But what I'm really missing is the possibility to have an incremental
variable reminding me of which line I'm processing, e.g.:

perl -wne 'my $i=0;/(\S+)\s+(\S+)/;print "$i $2\n";$i++' e.dat

of course it doesnt work, but I'd like to have a way for $i to be
incremented - there is a hope of accomplishing this?



Re: perl implicit loop switch

Check out the special variable "$."

This should work:

perl -wne '/(\S+)\s+(\S+)/;print "$. $2\n";' e.dat

Re: perl implicit loop switch

Quoted text here. Click to load it

see the $. variable in "perldoc perlvar":

    perl -wne '/(\S+)\s+(\S+)/;print "$. $2\n"' e.dat

Try inserting a line like:


(or any other line that will fail to match your pattern) into e.dat
somewhere besides the 1st line, and see if you like its output...

... then apply this rule:

   You should never use the dollar-digit variables unless you have
   first ensured that the match *succeeded*.

    perl -wne 'print "$. $2\n" if /(\S+)\s+(\S+)/' e.dat
    perl -wlne 'print "$. $2" if /(\S+)\s+(\S+)/' e.dat

Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher0cmdat/"

Re: perl implicit loop switch

Quoted text here. Click to load it

You say "of course" it doesn't work.  But do you know why?  The
incrementing is happening just fine.  But because the "my $i=0" is
inside the loop, each time is getting a new $i (handily set to 0).

The other posts pointing at $. are probably better for something this
simple, but your solution would work fine if you took the assignment out
of the loop:

perl -wne 'BEGIN /(\S+)\s+(\S+)/;print "$i $2\n";$i++' e.dat

or even

perl -wne '$i++ ;/(\S+)\s+(\S+)/;print "$i $2\n";' e.dat


Site Timeline