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?
PERL QX FUNCTION. Description. This function is a alternative to using back-quotes to execute system commands. For example, qx ls − l will execute the UNIX ls command using the -l command-line option. You can actually use any set of delimiters, not just the parentheses.
Strip out lines Use perl -nle 'print if ! … ' to say “print, except for the following cases.” Practical uses include omitting lines matching a regular expression, or removing the first line from a file.
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:
perl -MO=Deparse -pe 's/(\d+)/localtime($1)/e'
outputs:
LINE: while (defined($_ = <ARGV>)) {
s/(\d+)/localtime($1);/e;
}
continue {
print $_;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With