[BNE-PM] The Perl one-liner
Derek Thomson
derek at wedgetail.com
Wed Sep 18 05:58:23 CDT 2002
Hi all,
Some of you may be wondering what all this Perl "one liner" business is
all about.
So, here's a quick intro ...
Perl is a useful and powerful programming language. However, it can also
be used from the command line, just like standard tools such as sed,
grep or sort (and can therefore be combined with these tools to work
great magic!).
The key to this use of Perl is the "-e" flag. This allows you to specify
Perl code to execute right on the command line. For example:
$ perl -e 'print "Hello, world\n"'
... outputs the string and exits.
Now, I hear you cry, this is not as good as (say) sed, as I must write a
loop to read in the input each time, like this:
$ perl -e 'while (<>) { s/Foo/Bar/g; print }'
... which changes all the Foo to Bar.
However, someone thought of that, and so you have the "-n" option, which
wraps your code in an invisible "while (<>) { ... }" loop. So we could
shorten the above as:
$ perl -ne 's/Foo/Bar/g; print'
All well and good, but it's so common that we want to read each line,
alter it and print the result, can't this be made even shorter? Yes,
with the "-p" option, which is the same as "-n", but prints the line
after each execution of the loop body.
$ perl -pe 's/Foo/Bar/g'
So, now we have re-invented "sed", but with the power of Perl regexes
available to us. That's a starting point - now the game is to do as much
as you can using these constructs (and any others - see the perlrun
manpage for more) in one line (usually 80 characters). It's a great way
to learn about these command line options, and how to use the implicit
argument variable "$_", to pack as much meaning into as little syntax as
possible.
You could start by re-inventing "grep" - a program which reads each line
of input, and prints only those lines that match a regular expression.
--
D.
More information about the Brisbane-pm
mailing list