Warning: Undefined array key "action" in /home/bakers/html/entryreply.php on line 5

Warning: Undefined variable $output in /home/bakers/html/entryreply.php on line 50

Warning: Undefined array key "EntrySubject" in /home/bakers/html/entryreply.php on line 51

Warning: Undefined variable $logintext in /home/bakers/html/entryreply.php on line 97

Warning: Undefined variable $reply_name in /home/bakers/html/entryreply.php on line 103

Warning: Undefined variable $reply_email in /home/bakers/html/entryreply.php on line 104
Perturb.org - interesting technology related things from around the internet

Perl: Quick extract variables from @ARGV

I'm a big fan of Getopt::Long, but sometimes I do not want to include a large module to extract two arguments. I wrote a quick function that will parse simple command line arguments and give you a hash of their values.

sub argv {
    state $ret = {};

    if (!%$ret) {
        for (my $i = 0; $i < scalar(@ARGV); $i++) {
            # If the item starts with "-" it's a key
            if ((my ($key) = $ARGV[$i] =~ /^--?([a-zA-Z_]\w*)/) && ($ARGV[$i] !~ /^-\w\w/)) {
                # If the next item does not start with "--" it's the value for this item
                if (defined($ARGV[$i + 1]) && ($ARGV[$i + 1] !~ /^--?\D/)) {
                    $ret->{$key} = $ARGV[$i + 1];
                    $ARGV[$i]    = $ARGV[$i++] = undef; # Flag key/val to be removed
                } else { # Bareword like --verbose with no options
                    $ret->{$key}++;
                    $ARGV[$i] = undef; # Flag item to be removed
                }
            }
        }
        @ARGV = grep { defined($_); } @ARGV; # Remove processed items from ARGV
    };

    if (defined($_[0])) { return $ret->{$_[0]}; } # Return requested item

    return $ret;
}

Note: I also wrote a similar implementation for PHP



Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 3.229.142.91
To prevent spam please submit by clicking the kitten: