>>>>> "BRH" == Bryan R Harris <bryan_r_har...@raytheon.com> writes:
BRH> I have a curiosity maybe someone here can help with. BRH> This code: BRH> @a=(1,2); BRH> map { $_ = 3 } @a; BRH> print join(",", @a), "\n"; BRH> ... prints "3,3". That map is changing the @a array as it goes through it. BRH> Good. bad. as jim points out, map aliases $_ to its input values. it does this more for efficiency (it doesn't need to copy the values) than for convenience to the coder. note that foreach modifier does the same thing (and also for loops). this aliasing can be useful as in: s/X/Y/g for @values ; but side effects done in map are a bad thing since map's purpose is to generate a new list from its values. it has the aliasing left in for speed and for compatibility with the other loops that alias. BRH> Now this: BRH> %a=(1,2); BRH> map { $_ = 3 } keys %a; BRH> print join(",", keys(%a)), "\n"; BRH> I expected this to print "3", but it doesn't -- it prints "1". BRH> If map sets $_ as an alias to the value, why isn't it changing BRH> the keys? why would you expect that? hash keys are not variables, values or anything but fixed strings. they are effectively readonly. it would make no sense to be able to modify them as that is really doing this: $new_key = mung( $old_key ) ; $hash{ $new_key } = delete $hash{ $old_key } that just moves the value from one key to another. if you set all the keys to 3 then you would end up with only one key/value which is 3 and its value would be a random value of all the hashes values (based on iterator ordering). now on the other hand aliasing the values of a hash is very cool. use the for modifier and this is very nice: s/foo/bar/ for values %hash ; we just edited all the values with that s/// op. you can do anything to $_ in there and that will change the value entries in the hash. uri -- Uri Guttman ------ u...@stemsystems.com -------- http://www.sysarch.com -- ----- Perl Code Review , Architecture, Development, Training, Support ------ --------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com --------- -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/