in reply to How to change an Array to a Hash

Hello alialialia,

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

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)
L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.