As already said you can feed a list to form an hash directly. But note venoth.ree added use warnings (and use strict too: never miss them) infact if your list is odd you can trap some unwanted behaviour:
perl -we "my %hash = @ARGV" Andy 1995 Sarah 1990 Sam 1992 UNEXPECTED Odd number of elements in hash assignment at -e line 1.
If you want to build the hash using a loop (ignoring odd element if present), you can use while as in:
@ARGV = qw( Andy 1995 Sarah 1990 Sam 1992 UNEXPECTED ); my %hash; while (my $key = shift @ARGV and my $val = shift @ARGV){ $hash{$key}=$val } # hash is: ("Sam", 1992, "Andy", 1995, "Sarah", 1990)
UPDATE you can spot the odd element before entering the loop: print qq(odd element $ARGV[-1] will be lost!\n) if @ARGV % 2 > 0; though.
If you want you can also explore List::Util pairs function: it warns on odd element assigning undef
L*use strict; use warnings; use List::Util qw(pairs); @ARGV= qw(Andy 1995 Sarah 1990 Sam 1992 UN); my %hash; for my $pairs (pairs @ARGV){ $hash{ $$pairs[0] } = $$pairs[1]; } Odd number of elements in pairs at -e line 1. # hash is: ("Sarah", 1990, "Andy", 1995, "UN", undef, "Sam", 1992)
In reply to Re: How to change an Array to a Hash (updated)
by Discipulus
in thread How to change an Array to a Hash
by alialialia
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |