Created
November 5, 2013 09:13
-
-
Save codescv/7316128 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w | |
# GistID: 7316128 | |
# example: argparse.pl arg1 arg2 arg3 --long-param x -l hh -a arg4 arg5 | |
# params = {"long"=>"x", "short"=>"hh", "switch-a":1} | |
# args = ("arg1", "arg2", "arg3", "arg4", "arg5") | |
use strict; | |
use 5.010; | |
my %switches = ( | |
"long-param" => ["param", "long"], | |
"s" => ["param", "short"], | |
"a" => ["switch", "switch-a"], | |
); | |
my %params; | |
my @args; | |
while (my $arg = shift) { | |
my $matched = 0; | |
for my $key (keys %switches) { | |
my ($type, $target) = @{$switches{$key}}; | |
if ($arg =~ /--$key=(.*)/) { | |
$params{$target} = $1; | |
$matched = 1; | |
} elsif ($arg eq "--$key") { | |
$params{$target} = 1; | |
$matched = 1; | |
} elsif ($arg eq "-$key") { | |
if ($type eq "param") { | |
$params{$target} = shift; | |
$matched = 1; | |
} elsif ($type eq "switch") { | |
$params{$target} = 1; | |
$matched = 1; | |
} | |
} | |
} | |
if (!$matched) { | |
push @args, $arg; | |
} | |
} | |
use Data::Dumper; | |
say "params: ", Dumper(\%params); | |
say "args: @args"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment