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"; }
In reply to 'each' syntax oddity? by SuperCruncher
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |