in reply to Creating Hashes from Switches

Getopt::Std (which you use but never use) gets you most of the way there.

#!/usr/bin/perl -w use strict; use Getopt::Std; use Data::Dumper; my %switches; getopts('x:o:d:m:', \%switches); print Dumper \%switches;

Running it gets you:

$ ./test.pl -o outputfile -x xmlfiles -d disk1 -m memory1 $VAR1 = { 'm' => 'memory1', 'd' => 'disk1', 'x' => 'xmlfiles', 'o' => 'outputfile' };

The problem is, of course, with your multi-valued options. If you could make one small change to the way you pass them into the program then this would be very simple.

#!/usr/bin/perl -w use strict; use Getopt::Std; use Data::Dumper; my %switches; getopts('x:o:d:m:', \%switches); foreach (keys %switches) { $switches{$_} = [ split /\s+/, $switches{$_} ]; } print Dumper \%switches;

The one problem is that you have to quote the multiple keys like this:

$ ./test.pl -o outputfile -x xmlfiles -d 'disk1 disk2' -m 'memory1 mem +ory2' $VAR1 = { 'm' => [ 'memory1', 'memory2' ], 'd' => [ 'disk1', 'disk2' ], 'x' => [ 'xmlfiles' ], 'o' => [ 'outputfile' ] };
--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re: Re: Creating Hashes from Switches
by kabel (Chaplain) on Sep 19, 2002 at 09:37 UTC
    for the @ARGV: make a block, local the @ARGV array and build it from the XML file. should work.
Re: Re: Creating Hashes from Switches
by johnirl (Monk) on Sep 19, 2002 at 11:22 UTC
    Thanks Dave,
    but how would this be implemented if I didn't know the switches until runtime?

    UPDATE
    Well now I feel stupid. It seems my code was working I just forgot to print the results. Duh!! Sorry

    j o h n i r l .

     Sum day soon I'Il lern how 2 spelI (nad tYpe)

      If you know that the first two arguments you'll get are the XML file and the output file then you can do something like this:

      #!/usr/bin/perl -w use strict; use Getopt::Std; use Data::Dumper; my %switches; %switches = splice(@ARGV, 0, 4); # parse the XML file and work out what other arguments # you're going to be passed. Use that info to build $fmt my $fmt = 'd:m:'; getopts($fmt, \%switches); foreach (keys %switches) { $switches{$_} = [ split /\s+/, $switches{$_} ]; } print Dumper \%switches;

      It's a bit fragile tho' as it assumes there will be spaces between the first two options and their arguments.

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg