Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify the "before-the loop" code when using "perl -ne"?

How do I specify the "before-the loop" code when using "perl -ne", without resorting to either BEGIN/END blocks or replacing "-n" with actually spelled-out while loop?

To explain in detail:

Say, I have the following Perl code:

use MyModule;
SETUP_CODE;
while (<>) {
    LOOP_CODE;
}
FINAL_CODE;

How can I replace that with a one-liner using perl -ne?

Of course, the loop part is handled by the -n itself, while the FINAL_CODE can be done using a trick of adding "} { FINAL_CODE" at the end; whereas the use statement can be handled via "-M" parameter.

So, if we had no SETUP_CODE before the loop, I could write the following:

perl -MMyModule -ne 'LOOP_CODE } { FINAL_CODE'

But, how can we insert SETUP_CODE here?

The only idea I have is to try to add it after the loop via a BEGIN{} block, ala

perl -MMyModule -ne 'LOOP_CODE } BEGIN { SETUP_CODE } { FINAL_CODE'

But this seems at best hacky.

Any other solution?

Just to be clear - I already know I can do this by either spelling out the while loop instead of using "-n" or by using BEGIN/END blocks (and might even agree that from certain points of view, doing "while" is probably better).

What I'm interested in is whether there is a different solution.

like image 528
DVK Avatar asked Sep 01 '25 10:09

DVK


2 Answers

Write BEGIN and END blocks without ceremony:

$ perl -lne 'BEGIN { print "hi" }
             print if /gbacon/;
             END { print "bye" }' /etc/passwd
hi
gbacon:x:700:700:Greg Bacon,,,:/home/gbacon:/bin/bash
bye
like image 120
Greg Bacon Avatar answered Sep 03 '25 15:09

Greg Bacon


Sneak your extra code into the -M option

perl -M'Module;SETUP CODE' -ne 'LOOP CODE'

 

$ perl -MO=Deparse -M'MyModule;$SETUP=1' -ne '$LOOP=1}{$FINAL=1'
use MyModule;
$SETUP = 1;
LINE: while (defined($_ = <ARGV>)) {
    $LOOP = 1;
}
{
    $FINAL = 1;
}
-e syntax OK
like image 31
mob Avatar answered Sep 03 '25 15:09

mob