develooper Front page | perl.beginners | Postings from April 2002

RE: assigning array to hash

Thread Previous | Thread Next
Shah, Urmil
April 26, 2002 14:55
RE: assigning array to hash
Message ID:
If you want to assign an array to a fixed key that is if you want something
like: one key -> multiple values(eg array)
you can use
my $label_hash{$key1} = [@array1];
   $label_hash{$key2} = [@array2];


-----Original Message-----
From: Felix Geerinckx []
Sent: Friday, April 26, 2002 9:17 AM
Subject: Re: assigning array to hash

on Fri, 26 Apr 2002 14:09:24 GMT, (Richard Noel Fell)

> Below is part of some code that reads from a file to an array and
> then attempts to assign the array to a hash.  I get no compiling
> errors, but %label_hash is empty. No doubt I am being stupid. Has
> anyone a suggestion how to fill the hash variable?
> Thanks,
> Dick Fell

This depends on what you mean by 'assigning the array to a hash'.
A hash consists of (key, value) pairs.

>    my %label_hash=@label_array;

This works if @label_array has an even number of elements, being 
equivalent with the following explicit assignments:

    	$label_hash{$label_array[0]} = $label_array[1];
    	$label_hash{$label_array[2]} = $label_array[3];

If the array has an odd number of elements, you get a fatal 'Odd 
number of elements in hash assignment' error.

But maybe you want to assign the elements of your array to the keys 
of your hash? This can be done as follows:

    	$label_hash{$_}++ for (@label_array);


To unsubscribe, e-mail:
For additional commands, e-mail:

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About