Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

New switches for perl(1)

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

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;
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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2025-06-23 18:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.