Disclaimer

The content of this blog is my personal opinion only. Although I am an employee - currently of Nvidia, in the past of other companies such as Iagination Technologies, MIPS, Intellectual Ventures, Intel, AMD, Motorola, and Gould - I reveal this only so that the reader may account for any possible bias I may have towards my employer's products. The statements I make here in no way represent my employer's position, nor am I authorized to speak on behalf of my employer. In fact, this posting may not even represent my personal opinion, since occasionally I play devil's advocate.

See http://docs.google.com/View?id=dcxddbtr_23cg5thdfj for photo credits.

Tuesday, December 16, 2008

I have a new BKM for argument list parsing in Perl, similar to my longstanding BKM in C/C++:




my $argv = {};

for( my @tmp_ARGV = @ARGV; my $arg = shift @tmp_ARGV; ) {
if(0) {}
elsif( $arg eq "-short" ) {
$argv->{test_length} = 'short';
}
elsif( $arg eq "-full" ) {
$argv->{test_length} = 'short';
}
else {
die "unrecognized command line argument: <$arg>";
}
}



I rather like creating a hash of options,
but if you prefer variables:


my $short;

for( my @tmp_ARGV = @ARGV; my $arg = shift @tmp_ARGV; ) {
if(0) {}
elsif( $arg eq "-short" ) {
$short = 1;
}
elsif( $arg eq "-full" ) {
$short = 0;
}
else {
die "unrecognized command line argument: <$arg>";
}
}



This can be made extensible, by calling subfunctions to parse, so-called argv-recognizers. These can recognize individual options, or parse a long way.


my $short;

for( my @tmp_ARGV = @ARGV; my $arg = shift @tmp_ARGV; ) {
if(0) {}
elsif( $arg eq "-short" ) {
$short = 1;
}
elsif( argv_parser1(\@tmp_ARGV) {}
elsif( argv_parser2(\@tmp_ARGV) ) {}
else {
die "unrecognized command line argument: <$arg>";
}
}



The following may be more uniform:


for( my @tmp_ARGV = @ARGV; my $arg = @tmp_ARGV[0]; shift @tmp_ARGV ) {
...
}


---

Why use this instead of Getopts? Getopts::Lomng? Etc.

Mainly

a) Getopts does not compose modules with different parsers

b) the above is trivial, easy to remember, and can be extended to handle any different argument syntax.

No comments: