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

Re: assigning array to hash

Thread Previous | Thread Next
From:
Felix Geerinckx
Date:
April 26, 2002 07:16
Subject:
Re: assigning array to hash
Message ID:
Xns91FCA5995A17Bfge123@209.85.157.220
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



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