I was playing with a Perl evalbot on freenode today. I came up with the following:
@array = split /\s*/, 'the quick brown fox jumps over the lazy dog';@h +ash{@array}++;print for sort keys %hash;
It is jumbled up like this because you have to get it all in one line for the bot.
It was pointed out to me by someone lurking in the bot room that @hash{@array}++ does not do what I think it does. He was right. I assumed that it created a new hash element for each of the elements of @array with the key being a value from @array and the value being 1.
I realized that I was wrong, but I wondered why it still worked. I took the discussion into #perl to get more input.
I was told by several users that it did the same as $hash{$array[-1]}++, and that I was wrong. No need to look any further.
The problem is that I then tested it both ways and found that the output was not the same. The difference is that $hash{$array[-1]}++ takes the last element of @array and creates a single hash element with value 1 and @hash{@array}++ does the same but it also creates hash elements for all of the other elements of @array with value undef.
A hash element with a value of undef is apparently different that a hash element that has never been created.
I pointed this out on the channel and I was told that while I was correct on this point, I should not use this property since it is probably a side effect of how hash slices are implemented. Also, it may confuse others.
I was just curious to get other opinions on this property regarding why it works and if it should be used in the above fashion if understood for what it really does or not.
Code tags added by GrandFather
In reply to postfix incrementing of hash slice by mjl69
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |