Archive for June, 2013

Perl arg parser

Monday, June 10th, 2013


I use this a lot when writing a simple perl script that I want to take args like –flag and –database=this and –comment=”This is a comment with spaces”

while($arg = shift) {

if(($s1,$s2) = $arg =~ /–(.*)=(.*)/) {
$l1 = lc $s1;
$s2 = $a if(($a) = $s2 =~ /^\”(.*)\”$/);
$arg{$l1} = $s2;
} elsif(($s1) = $arg =~ /–(.*)/) {
$l1 = lc $s1;
$arg{$l1} = 1;
}
}

Stick it in the top of the script, and you can then just use

if($arg{‘flag’}) {

}

$comment = $arg{‘comment’};

and so on and so forth.