Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re^3: Hash assignment: Undocumented feature?

by 5mi11er (Deacon)
on Aug 11, 2013 at 17:03 UTC ( #1049015=note: print w/replies, xml ) Need Help??

in reply to Re^2: Hash assignment: Undocumented feature?
in thread Hash assignment: Undocumented feature?

Perhaps you're new enough to the concept of a hash to not fully understand that any hash "bucket" acts the same as an array "bucket". In other words,
    $hash{'bucket'} = 'something';
is similar in concept to

If you then, say
    $array[5]='something else';
hopefully you understand that $array[5] has been written over with the new information; just extend that concept to
    $hash{'bucket'} = 'something else';

So, no this is not new behavior, but the way hashes, across all the languages that implement some sort of hash, are supposed to work.


Replies are listed 'Best First'.
Re^4: Hash assignment: Undocumented feature?
by fsavigny (Novice) on Aug 11, 2013 at 17:54 UTC

    No, no. I am not surprised at all (nor new to the fact) that $hash{'bucket'} = 'something'; overwrites anything that took 'something''s place before. (I thought I had hinted as much in my original post; sorry if that wasn't clear enough.) That was in fact the one and only way of modifying a hash value I knew.

    For that reason, it was clear to me that if you specify a key twice, one of them must have to go, since otherwise, the hash is no longer a hash. But it wasn't obvious to me which of the values would prevail. Even though the last one is arguably the most intuitive choice, I wouldn't have wanted to bank on it.

    What contributed to my wondering was probably this easy interchangeability of arrays and hashes: ('foo', 2, 'bar', 'pepper') can be assigned to @some_array_variable or %some_hash_variable, or you could assign it to the former and then say %some_hash_variable = @some_array_variable. But

    %some_hash_variable = ('foo', 2, 'bar', 'pepper', 'foo', 4); # is crucially different from @some_array_variable = ('foo', 2, 'bar', 'pepper', 'foo', 4);

    That's what I found interesting about it, and no, I did not find it completely obvious which value %some_hash_variable would have. (My secret motto is "You never know with Perl".) But now I know. It's a nice feature, and now I can rely on it.

Re^4: Hash assignment: Undocumented feature?
by ikegami (Pope) on Aug 12, 2013 at 19:38 UTC
    Bucket has a special meaning to hash tables, what hashes implement. You are talking about elements of hashes and arrays.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1049015]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (2)
As of 2017-03-27 05:04 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (315 votes). Check out past polls.