in reply to Re: GetOpts not working:
in thread GetOpts not working:

Heres another way:
use strict; use warnings; my @ARGV = qw(-infile data_in.bin -outfile data_out.bin); my %args; for ( 0 .. $#ARGV / 2 ) { my $switch = shift(@ARGV); my $value = shift(@ARGV); $args{$switch} = $value; } print "Infile: $args{-infile}\n", "Outfile: $args{-outfile}" if ( exis +ts $args{-infile} && exists $args{-outfile} );
I am growing to really like hashes, and I think im about ready to start doing like hash of arrays, so i can have multiple values for a single hash key. Isnt that how this works?
my %hash = { key => [value_1, value_2, value_3, value_4]};
I just wonder how i would print all the values
Edit: I figured it out, thanks

Replies are listed 'Best First'.
Re^3: GetOpts not working:
by hippo (Archbishop) on Dec 10, 2015 at 09:13 UTC

    There appears to be no benefit to your use of a for loop in that code. Standard hash population means that it isn't needed.

    use strict; use warnings; my @ARGV = qw(-infile data_in.bin -outfile data_out.bin); my %args = @ARGV; print "Infile: $args{-infile}\n", "Outfile: $args{-outfile}" if ( exis +ts $args{-infile} && exists $args{-outfile} );

    works just the same. HTH.

    PS. I wouldn't use @ARGV for a lexical variable name since it ordinarily has a special meaning.

      I tested it and it does indeed work. How is this possible? How does it know to put the filenames into their respective places? Does it somehow auto assign a key/value pair? Im just as confused lol, because I thought you had to shift the array to get the next value, but somehow it automatically did it :0 This is what i did:
      use strict; use warnings; my %args = @ARGV; print "Infile: $args{-infile}\n", "Outfile: $args{-outfile}" if ( exis +ts $args{-infile} && exists $args{-outfile} );

      I fed it '-infile data_in.bin -outfile data_out.bin'. and it almost seems like it has assigned key/value pairs based off of my thought patterns lol <.<

      I guess what i am asking is, how did it build the hash? and why did my %args = @ARGV; build it correctly like that. How is 'data_in.bin' and 'data_out.bin' not a key? if key -infile contains value 'data_in.bin' then what assigned 'data_in.bin' to be its value? there was no shifting or anything to loop through the input args
        Does it somehow auto assign a key/value pair?

        Essentially, yes. When you assign directly to a hash it expects a list of key-value pairs. This is why you sometimes see the warning "Odd number of elements in hash assignment" because the list must be even-sized so that each key has a corresponding value. These two assignments are effectively the same:

        my %foo = ( baz => 1, frob => 'quux' ); my %bar = ( 'baz', 1, 'frob', 'quux' );

        There's more about this in List value constructors in perldoc.

        Does that help?