perl implicit loop switch

A

alexxx.magni

<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?

thanks!


alessandro
 
K

Krishna Chaitanya

Check out the special variable "$."

This should work:

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

Tad J McClellan

<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?


see the $. variable in "perldoc perlvar":

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

Try inserting a line like:

foobar

(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
or
perl -wlne 'print "$. $2" if /(\S+)\s+(\S+)/' e.dat
 
D

Darren Dunham

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?

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 {$i=1;} /(\S+)\s+(\S+)/;print "$i $2\n";$i++' e.dat

or even

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,006
Latest member
LauraSkx64

Latest Threads

Top