Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert Perl one-liners into complete scripts?

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?

like image 858
Stefan Lasiewski Avatar asked May 12 '10 20:05

Stefan Lasiewski


People also ask

What is QX in Perl?

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.

What is Perl NLE?

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.


1 Answers

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.

like image 119
Eric Strom Avatar answered Nov 15 '22 18:11

Eric Strom