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

Leave A Reply
All content licensed under the Creative Commons License