I find a lot of Perl one-liners online. Sometimes I want to convert these one-liners into a script, because otherwise I'll forget the syntax of the one-liner.
For example, I'm using the following command (from nagios.com):
tail -f /var/log/nagios/nagios.log | perl -pe 's/(\d+)/localtime($1)/e'
I'd to replace it with something like this:
tail -f /var/log/nagios/nagios.log | ~/bin/nagiostime.pl
However, I can't figure out the best way to quickly throw this stuff into a script. Does anyone have a quick way to throw these one-liners into a Bash or Perl script?
You can convert any Perl one-liner into a full script by passing it through the
B::Deparse
compiler backend that generates Perl source code:outputs:
The advantage of this approach over decoding the command line flags manually is that this is exactly the way Perl interprets your script, so there is no guesswork.
B::Deparse
is a core module, so there is nothing to install.Take a look at perlrun:
So, simply take this chunk of code, insertyour code at the "# your program goes here" line, and viola, your script is ready!
Thus, it would be:
Robert has the "real" answer above, but it's not very practical. The -p switch does a bit of magic, and other options have even more magic (e.g. check out the logic behind the -i flag). In practice, I'd simply just make a bash alias/function to wrap around the oneliner, rather than convert it to a script.
Alternatively, here's your oneliner as a script: :)
The while loop and the print is what -p does automatically for you.
That one's really easy to store in a script!
The
-e
option introduces Perl code to be executed—which you might think of as a script on the command line—so drop it and stick the code in the body. Leave-p
in the shebang (#!
) line.In general, it's safest to stick to at most one "clump" of options in the shebang line. If you need more, you could always throw their equivalents inside a
BEGIN {}
block.Don't forget
chmod +x ~/bin/nagiostime.pl
You could get a little fancier and embed the
tail
part too:This works because the code written for you by
-p
uses Perl's "magic" (2-argument)open
that processes pipes specially.With no arguments, it transforms
nagios.log
, but you can also specify a different log file, e.g.,There are some good answers here if you want to keep the one-liner-turned-script around and possibly even expand upon it, but the simplest thing that could possibly work is just:
Perl will recognize parameters on the hashbang line of the script, so instead of writing out the loop in full, you can just continue to do the implicit loop with -p.
But writing the loop explicitly and using -w and "use strict;" are good if plan to use it as a starting point for writing a longer script.