This hunk of code will accept -m0 -m=0 and -m 0 as equivalents. I'm working on my figlet in perl implementation and decided I should accept standard figlet style switches which are -m0 and -m 0. I was previously using -s and hence only accepted -m=0. I felt this warranted backwards compatibility.

UPDATE: Just thought I'd add that while it's not so obvious this does not support switch clustering, though upon inspection the reason is obvious.

my %opts; #Arguments that take no options $opts{$_} = undef for qw(A D E L R X c demo help l r x); #Arguments that must take options # (may is easily doable with a lookahead in the do but # then you cannot accept negative numbers as values # without them being adjoined to the switch) # do{ if( $ARGV[$i+1] =~ /^-/ ){ 1; }else{ $i--; shift;} } $opts{$_} = "0 but true" for qw(I d f m w); for(my $i=0; $i <= scalar @ARGV; $i++){ #End arguments at -- shift && last if $ARGV[$i] eq '--'; #UPDATE: The sort gives priority to longer switches foreach my $key ( sort { length($b)-length($a) } keys %opts){ if( $ARGV[$i] =~ /^-$key=?(.*)/ ){ #Get rid of the switch, keep $i in sync shift; $i--; #Set the value (if adjoined or shift else 1) $opts{$key} = defined($1) && $1 ne '' ? $1 : defined($opts{$key}) ? do{$i--; shift} : 1; #Short circuit last; } } } #Clear unseen switches that take values to not pass along false positi +ves $_ eq '0 but true' && ($_ = undef) for values %opts;

Replies are listed 'Best First'.
Re: Triple syntax getopt
by belg4mit (Prior) on Feb 07, 2002 at 22:36 UTC
    *sigh* Nothing's perfect. I was working on something else when I discovered that the code recognizes -demo as equivalent to -d=emo. I have updated the code with a fix, it sorts the arguments by length so -demo is seen first. This of course means you can't have -d=emo in the adjoined format. The impact of this can of course be softened by picking your switches wisely.

  • Avoid similar switches, user's appreciate this ++.
  • If similar switches do not accept values there is no spoon^H^H^H^H^Hproblem.
  • GNU style --long-options also pose no problem.

I of course welcome any suggestions for handling the clash better.

--
perl -pe "s/\b;([st])/'\1/mg"