hoopajoo.net
Looping over data
Looping over data
⇐ Back to One Liners

Questions, comments, or corrections? Send me a message.

Perl provides a few ways to loop over data and manipulate it. Let's say you want to just print the lines of a file that match a regex but prefix it with some string. You might start with a perl program like:

#!/usr/bin/perl

open( IN, $ARGV[0] );
while( $line = <IN> ) {
 print "** $line" if $line =~ /^\d+/;
}
close( IN );
This will print all lines that start with numbers, and prefix the line with some "&"'s. Now this would be way too much to type at a prompt, but perl has a switch to eliminate the whole while loop, so all you're left with is the print statement, so you could do it like this:
perl -ne 'print "** $_" if /\d+/' myfile.txt
The -n means wrap the script in while(<>){} and the -e means to execute the next part instead of using a script file, so myfile.txt isn't considered a script, it's the input data. Read up on different switches in the perlrun man page.