P is for Practical | |
PerlMonks |
Map: Thou Has't Confounded Me For The Last Time! (Referring To The Array You Are Assigning To In Map)by Revelation (Deacon) |
on Feb 14, 2005 at 05:34 UTC ( [id://430695]=perlquestion: print w/replies, xml ) | Need Help?? |
Revelation has asked for the wisdom of the Perl Monks concerning the following question:
In perldoc -f map, one may read:
%hash = map { getkey($_) => $_ } @array;
is just a funny way to write
Under this pretense, this morning I wrote something that roughly looked like ({grin} I'm not using map in a void context, by the way ): which I assumed, in accordance with perldoc, would roughly translate to: Obviously this isn't a literal translation, but that's unimportant right now. What confused me was that Perl threw an error (using strict), telling me that I needed to define %res in the line: } if !$res{$_}; Thus, adding a my %res to the beginning of my map code solved that problem. This was indicative of a larger problem, however; when benchmarking the two hash generations, it became rather obvious that Perl wasn't checking to see if that key already existed in my hash: upon investigation, it turns out that when inside map, you can not refer to the array (or hash) you are assigning to at all: simply throws an error, because $a[0] will return undefined until the map call is completed. As far as I can tell this behavior is not documented and unexplainable. Perl -MO=Deparse did not provide any explanation either. I have always been under the impression that map assigns to a list, like foreach does, but this doesn't seem to be true. In truth, judging from my experiences as well as the form of a map call, map returns a list that the array or hash you have created is _then_ set to. This, however, doesn't parallel Perl's documentation. Am I doing something stupid? Is Perl's documentation wrong? Are we both wrong? I'd love for somebody to explain this behavior with respect to map as well as any other general quirks of map's behavior if there are some. Update: I was not commenting on this functionality of map being counterintuitive (I understand that map is returning a list that is then assigned to an array); rather, that it didn't paralel Perl's documentation (which, to me, indicated that map had some magic associated with it, that changed this more 'natural' behavior, so that @b = map { $_ } @a would translate to push(@b,$_) for @a;.) While PodMaster seems to think that I've taken the documentation out of context, in the context I read it in--which I assume is consistent with an experienced (albeit self-taught and in no way an expert) Perl programmer would read it, this behavior was a bit confusing. I was hoping that my post would yield an explanation as to how the differences in behavior link to the opcodes associated with the these different functions. Gyan Kapur The Worst Node Upvoter
Back to
Seekers of Perl Wisdom
|
|