If, like me, the vast majority of oneliners you write are -n or -p ones, you'll probably have cursed at the verbosity and unwieldiness of the -e'BEGIN { $foo } s/bar/baz; END { $quux }' construct.
Hey, I thought, I can do better than that.
So I ripped apart the Getopt::Std code and based this script on it, which adds two options to Perl:
-B
This works just like -e, except it also wraps the code in a BEGIN block.
-E
This also works like -e, except it wraps the code in a END block.
Enjoy.
Update: changed hardcoded location of Perl binary to $^X in last line as per bart's suggestion.
#!/usr/bin/perl -w
use strict;
my %blockname = (
e => '%s;',
B => '; BEGIN { %s };',
E => '; END { %s };',
);
my @arg;
while (@ARGV && (my ($switch, $rest) = $ARGV[0] =~ /^-(.)(.*)/)) {
if ($rest eq '-') { # early exit if --
push @arg, @ARGV;
last;
}
if ($switch !~ /[BEe]/) {
push @arg, shift @ARGV;
next;
}
shift (@ARGV);
if (not length $rest) {
if(@ARGV) {
$rest = shift (@ARGV);
}
else {
$! = 2; # emulate perl(1)
die "No code specified for -$switch.";
}
}
push @arg, -e => sprintf $blockname{$switch}, $rest;
}
exec { $^X } $^X, @arg;
You've hardcoded your path to your perl binary in the script. Maybe that's OK, because it's hardwired in the shebang line as well... but personally, I would still prefer use of the special variable $^X, anyway. In your case, it also will contain the value '/usr/bin/perl'. But it will make less problems for maintenance, for people whose perl is in another location.
I briefly thought about this actually. Didn't know about $^X though - I guess I should crack the cover on perlvar again sometime. :) Thanks for the suggestion, accepted.