Last night I was experimenting with XML::Parser, trying to parse an XML document. I encountered what I consider to be a pretty strange syntax/context oddity.
my @array = qw(foo bar); while (my ($attrib, $value) = each (@array) ) { print "$attrib=$value\n"; }
produces the error message:
Type of arg 1 to each must be hash (not private array) at test.pl line 2, near "@array) "

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:

my @array = qw(foo bar); while (my ($attrib, $value) = each (my %hash = @array) ) { print "$attrib=$value\n"; }
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:
Type of arg 1 to each must be hash (not list assignment) at test.pl line 2, near "@array) "

So I decided to insert another line before the while statement, as shown below:

my @array = qw(foo bar); my %hash = @array; while (my ($attrib, $value) = each (%hash) ) { print "$attrib=$value\n"; }
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).

In reply to 'each' syntax oddity? by SuperCruncher

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.