in reply to Modifying $_ in foreach (%hash)
Observe this experiment, which is relevant to your discussion of what happens when a hash argument is passed to a subroutine:
sub increment { $_++ foreach @_; } my %hash = qw(a 1 b 2 c 3); increment(%hash); print "$_ => $hash{$_}\n" for sort keys %hash;
The output will be:
a => 2 b => 3 c => 4
As others have pointed out, hash keys cannot be modified. And in our increment() subroutine, $_ is an alias to each value in @_, which aliases each key and value in %hash.
What is most likely to cause surprise to the coder is that had we passed the following to our increment() sub, we would get an exception thrown:
increment(qw(a 1 b 2 c 3)); ... Modification of a read-only value attempted at...
The surprising behavior in the case of passing the hash is that Perl's error handling doesn't report the attempt to modify a hash key. I can't really say whether it should report such a thing -- it might have been decided intentionally that was not desirable. Or it could have just not been noticed that there's a path to attempt to modify hash keys through aliasing.
If you look at the operations that must be provided when tieing a hash, you'll not find a hash key modification operation, though. Looking at Tie::Hash we see that the hash operations are TIEHASH, STORE, FETCH, FIRSTKEY, NEXTKEY, EXISTS, DELETE, CLEAR, and SCALAR. In perltie we see additional methods mentioned: UNTIE, and DESTROY. But there's no method such as RENAME or MODKEY.
Keep in mind that conceptually modifying a hash key makes about as much sense as modifying an array index. You cannot change an array index, you can only change which index a value is stored in. While hashes are different than arrays in that they have no inherent order, and that their indices are strings, they are similar in that their indices are immutable. Additionally, even were it possible to modify a hash key, the result would be a new hashing outcome, just as changing a character in a document that is passed through a SHA1 hashing algorithm should cause the resulting SHA1 to change. If the hashing outcome changes, the bucket location changes, so modification of a hash key would only work if the data were moved to the new location.
Dave
|
|---|