SuperCruncher has asked for the wisdom of the Perl Monks concerning the following question:
produces the error message:my @array = qw(foo bar); while (my ($attrib, $value) = each (@array) ) { print "$attrib=$value\n"; }
Peculiar, I thought--why can't the array be "automagically" converted to a hash? But anyway.... I know I can create a hash by assigning an array to a hash, and although each requires a HASH, I thought any expression that evaluates to a hash would be ok. So I try the following code:
I expected that to work: surely the my %hash = @array code is evaluated first, resulting in a hash. But this code didn't work either, I got the error:my @array = qw(foo bar); while (my ($attrib, $value) = each (my %hash = @array) ) { print "$attrib=$value\n"; }
So I decided to insert another line before the while statement, as shown below:
This did finally have the desired effect, but it seems incredibly redundant and un-Perl-like to have to have the array to hash assignment as a separate statement. Obviously if I want to create a hash, perl needs to create a hash table to do the look-ups so hashes aren't identical to arrays, but it seems strange that it can't automatically do this, especially when many Perl operators and functions act in magical ways (e.g. the ++ operator on strings).my @array = qw(foo bar); my %hash = @array; while (my ($attrib, $value) = each (%hash) ) { print "$attrib=$value\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(crazyinsomniac) Re: 'each' syntax oddity?
by crazyinsomniac (Prior) on Mar 07, 2002 at 13:22 UTC | |
|
Re: 'each' syntax oddity?
by steves (Curate) on Mar 07, 2002 at 14:34 UTC | |
|
Why do Perlers hate C-style for-loops, especially when they're called for?
by dragonchild (Archbishop) on Mar 07, 2002 at 14:39 UTC | |
by merlyn (Sage) on Mar 07, 2002 at 15:03 UTC | |
|
Re: 'each' syntax oddity?
by impossiblerobot (Deacon) on Mar 07, 2002 at 14:42 UTC |