The Ad-Hoc Command Line
Perl, like the other great Unix tools awk, sed, and grep, can be used to write mini-programs on the command line.
$ perl -e 'print 43*12,"\n";' 516
Above, the “e” option takes the program string to run. Use the “n” option to let the program execute for in line in the STDIN stream (often another utility output).
$ /sbin/ifconfig |perl -ne 'if (/addr:(.+?) /) {print "ip=$1\n";}' ip=192.168.0.101 ip=127.0.0.1
This loops over each line in the ifconfig command output, and looks for the IP addresses in the line and prints it on STDOUT.
Also, use the “p” option like the “e” option, but it will print out the line after execution. Typically you will alter the line in the program.
$ /sbin/ifconfig |perl -pe 's/\d+(\.\d+){3}/x.x.x.x/g;' eth0 Link encap:Ethernet HWaddr 00:03:47:FB:yy:yy inet addr:x.x.x.x Bcast:x.x.x.x Mask:x.x.x.x UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 ...
This little example locates IP address patterns in the output and replaces them with the x.x.x.x mask. Nothing too useful here, but I trust you’ll get the idea.
The trick here is that the input line is assigned to the special $_ variable, which in Perl is the default variable. It is often not specified for brevity and is ususally the expected result of the previous operation (like a read or subroutine parameter) that you want to use.