mjl69 has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: postfix incrementing of hash slice
by BrowserUk (Patriarch) on Oct 01, 2006 at 04:47 UTC | |
|
Re: postfix incrementing of hash slice
by ysth (Canon) on Oct 01, 2006 at 05:24 UTC | |
|
Re: postfix incrementing of hash slice
by shmem (Chancellor) on Oct 01, 2006 at 09:00 UTC | |
by cdarke (Prior) on Oct 01, 2006 at 11:12 UTC | |
by ysth (Canon) on Oct 01, 2006 at 17:26 UTC | |
|
Re: postfix incrementing of hash slice
by cdarke (Prior) on Oct 01, 2006 at 11:28 UTC | |
by Hue-Bond (Priest) on Oct 01, 2006 at 12:30 UTC |