That's not exactly what it does. It's functionally the programmatic reverse of the array:
push @{ $First{ $A[$_] } }, $_ for (0..$#A);
Let's take it from the inside out:
$A[$_] -- the element of @A at the current index
$First{ $A[$_] } -- the previous line is a key in %First
@{ } -- and the associated value is an anonymous array
So what the code does is, loop over the number of elements of @A. (If it has ten, the loop goes from 0 to 9).
For each of those indices, the value at that index becomes a key in %First, and the value is the element's index, stored in an anonymous array. We have something like this:
Elements of @A:
0 zero
1 one
2 two
Elements of %First:
zero [ 0 ]
one [ 1 ]
two [ 2 ]
While we can look something up in @A by its index, we can look up the index in %First if we know the something.
Oh, and in Perl hashes have something called auto-vivification. If you access a hash key that doesn't exist (and try to put data there), the key will be created. (Useful, once you get used to it.) | [reply] [d/l] [select] |
Thanks Chromatic. I think that I misinterpreted the Camel Book statement that "Hash values do not spring into existence upon reference." They may not spring into existence upon REFERENCE, but they do spring into existence if something tries to insert a value there. Now it makes sense.
| [reply] |
Hi,
Thank you for your kind words. I'm sure my writing falls
far short of canonization potential, but I'm flattered
nonetheless. :-)
chromatic has a great
answer to your
question. The quality and helpfulness of the people here at
Perl Monks is a constant source of amazement for me. As
he describes, I am utilizing auto-vivification in that terse
burst of code to reverse the array's indices and values.
To find a value in an array, you must know its index. We
build the hash to be able to find the indices when we know
the value. All that punctuation lets us define and assign
to the hash entry at once.
Good luck.
Russ
| [reply] |