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

RE: assigning array to hash

Thread Previous | Thread Next
From:
Shah, Urmil
Date:
April 26, 2002 14:55
Subject:
RE: assigning array to hash
Message ID:
87EA450621E2D211B6EE0000F8CD2957109B3608@dlee07.itg.ti.com
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];
      ...
      ...


Urmil  


-----Original Message-----
From: Felix Geerinckx [mailto:felix_geerinckx@hotmail.com]
Sent: Friday, April 26, 2002 9:17 AM
To: beginners@perl.org
Subject: Re: assigning array to hash


on Fri, 26 Apr 2002 14:09:24 GMT, fell01@rcn.com (Richard Noel Fell)
wrote: 

> 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];
    	etc...

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);

-- 
felix



-- 
To unsubscribe, e-mail: beginners-unsubscribe@perl.org
For additional commands, e-mail: beginners-help@perl.org

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About