in reply to Parsing command line options without knowing what they are
I never use getOpts of any form, and rarely use programs that use those conventions, so I've probably missed some rules. And it would probably need to be invoked at BEGIN{} time to be effective, but it's easier to play with this way.
This is hardly exhaustively tested, but it might form the basis of something useful:
#! perl -lw use strict; use Data::Dump qw[ pp ]; sub getOpts { my %opts; my @toDelete; for( my $i=0; $i < @ARGV; ++$i ) { $_ = $ARGV[ $i ]; if( m[^-(.)(.*)$] ) { my( $first, $rest ) = ( $1, $2 ); push @toDelete, $i; if( ! defined $first ) { next; } elsif( $first eq '-' ) { if( $rest eq '') { last; } if( $ARGV[ $i+1 ] =~ m[^-] ) { if( $rest =~ m[^no(.+)$] ) { $opts{ $1 } = 0; } else { $opts{ $rest } = 1; } } else { $opts{ $rest } = $ARGV[ ++$i ]; push @toDelete, $i; } } else { $opts{ $_ } = 1 for $first, split'',$rest; } } } splice @ARGV, $_, 1 for reverse @toDelete; return %opts; } my %opts = getOpts(); print "@ARGV\n", pp \%opts; __END__ c:\test>perl getOpts.pl -abc --def --ghi jkl -m -o fred bill --tuv wxy +z fred bill { a => 1, b => 1, c => 1, def => 1, ghi => "jkl", "m" => 1, o => 1, tu +v => "wxyz" } c:\test>perl getOpts.pl -abc --def --ghi jkl -m -- -o fred bill --tuv +wxyz -o fred bill --tuv wxyz { a => 1, b => 1, c => 1, def => 1, ghi => "jkl", "m" => 1 } c:\test>perl getOpts.pl -abc 12345 --def --ghi jkl -m -- -o fred bill +--tuv wxyz 12345 -o fred bill --tuv wxyz { a => 1, b => 1, c => 1, def => 1, ghi => "jkl", "m" => 1 } c:\test>perl getOpts.pl -abc 12345 --def --ghi jkl -m -o fred bill --t +uv wxyz 12345 fred bill { a => 1, b => 1, c => 1, def => 1, ghi => "jkl", "m" => 1, o => 1, tu +v => "wxyz" } c:\test>perl getOpts.pl -abc --def 12345 --ghi jkl -m -o fred bill --t +uv wxyz fred bill { a => 1, b => 1, c => 1, def => 12345, ghi => "jkl", "m" => 1, o => 1 +, tuv => "wxyz" } c:\test>perl getOpts.pl -abc --def 12345 --noverbose --ghi jkl -m -o f +red bill --tuv wxyz fred bill { a => 1, b => 1, c => 1, def => 12345, ghi => "jkl", "m" => 1, o => 1 +, tuv => "wxyz", verbose => 0 } c:\test>perl getOpts.pl -abc --def 12345 --noverbose --ghi jkl -m -o f +red --o bill --tuv wxyz fred { a => 1, b => 1, c => 1, def => 12345, ghi => "jkl", "m" => 1, o => " +bill", tuv => "wxyz", verbose => 0 }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Parsing command line options without knowing what they are
by DrWhy (Chaplain) on Nov 25, 2010 at 19:41 UTC | |
by BrowserUk (Patriarch) on Nov 25, 2010 at 19:48 UTC | |
by DrWhy (Chaplain) on Nov 25, 2010 at 20:09 UTC | |
by BrowserUk (Patriarch) on Nov 25, 2010 at 20:59 UTC |