Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

New switches for perl(1)

by Aristotle (Chancellor)
on Apr 21, 2003 at 13:06 UTC ( #251986=sourcecode: print w/replies, xml ) Need Help??
Category: Utility Scripts
Author/Contact Info /msg Aristotle

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:

This works just like -e, except it also wraps the code in a BEGIN block.
This also works like -e, except it wraps the code in a END block.


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;
    if ($switch !~ /[BEe]/) {
        push @arg, shift @ARGV;
    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;
Replies are listed 'Best First'.
Re: New switches for perl(1)
by bart (Canon) on Apr 22, 2003 at 06:37 UTC
    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.
    exec { $^X } $^X, @arg;
      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.

      Makeshifts last the longest.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: sourcecode [id://251986]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2021-11-28 18:19 GMT
Find Nodes?
    Voting Booth?

    No recent polls found