tags:

views:

66

answers:

2

So at the command line I can conveniently do something like this:

perl -pne 's/from/to/' in > out

And if I need to repeat this and/or I have several other perl -pne transformations, I can put them in, say, a .bat file in Windows. That's a rather roundabout way of doing it, of course. I should just write one perl script that has all those regex transformations.

So how do you write it? If I have a shell script containing these lines:

perl -pne 's/from1/to1/' in > temp
perl -pne 's/from2/to2/' -i temp
perl -pne 's/from3/to3/' -i temp
perl -pne 's/from4/to4/' -i temp
perl -pne 's/from5/to5/' temp > out

How can I just put these all into one perl script?

+8  A: 

-e accepts arbitrary complex program. So just join your substitution operations.

perl -pe 's/from1/to1/; s/from2/to2/; s/from3/to3/; s/from4/to4/; s/from5/to5/' in > out

If you really want a Perl program that handles input and looping explicitely, deparse the one-liner to see the generated code and work from here.

> perl -MO=Deparse -pe 's/from1/to1/; s/from2/to2/; s/from3/to3/; s/from4/to4/; s/from5/to5/'
LINE: while (defined($_ = <ARGV>)) {
    s/from1/to1/;
    s/from2/to2/;
    s/from3/to3/;
    s/from4/to4/;
    s/from5/to5/;
}
continue {
    print $_;
}
-e syntax OK
daxim
Whoa, I think I'm starting to fall in love with perl...
polygenelubricants
+5  A: 

Related answer to the question you didn't quite ask: the perl special variable $^I, used together with @ARGV, gives the in-place editing behavior of -i. As with the -p option, Deparse will show the generated code:

perl -MO=Deparse -pi.bak -le 's/foo/bar/'
BEGIN { $^I = ".bak"; }
BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
    chomp $_;
    s/foo/bar/;
}
continue {
    print $_;
}
hobbs