Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I am a newbie to perl, May I know how I can get all the selected options from GetOptions() in Getopt::Long module.

My GetOptions looks like the below GetOptions( 'a' => \$a, 'b' => \$b, 'c' => \$c, - - 'z' => \$z );

May I know how I can get only the selected options?
Thanks, Tom

Replies are listed 'Best First'.
Re: Getting selected options from GetOptions()
by GrandFather (Saint) on Dec 16, 2009 at 21:11 UTC

    Tell us more of what you want to do. It may be that you want to build a dispatch table then iterate over the entered options. Something like:

    use strict; use warnings; use Getopt::Long; my %options; my %dispatch = ( a => \&doA, b => \&doB, c => \&doC, ); GetOptions (\%options, 'a:s', 'b:s', 'c:s'); for my $option (keys %options) { $dispatch{$option}->($options{$option}) if exists $dispatch{$optio +n}; } sub doA { my ($param) = @_; print "Hello world\n"; } sub doB { my ($param) = @_; print "Do da dispatch\n"; } sub doC { my ($param) = @_; print "mu\n"; }

    given the command line '--a --b --c' prints:

    mu Hello world Do da dispatch

    True laziness is hard work
Re: Getting selected options from GetOptions()
by runrig (Abbot) on Dec 16, 2009 at 20:40 UTC
    E.g.:
    if ($a) { print "a was selected\n"; }
    If you want something more robust, I suggest a hash, e.g. (not tested):
    my %opts; GetOptions(map { ($_ => \$opts{$_}) } "a".."z"); $opts{$_} and print "$_ was selected\n" for "a".."z";
      The problem is that , there are more than 30 options, and I dont want to write like 30 if statements to get the selected options. Is there any effective way to find this?

      Thanks,
      Tom

        Using runrig's example:

        my %opts; GetOptions(map { ($_ => \$opts{$_}) } "a".."z"); my @selected = grep { $opts{$_} } keys %opts;
        Thanks much.
        -Tom
Re: Getting selected options from GetOptions()
by planetscape (Chancellor) on Dec 16, 2009 at 21:43 UTC