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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.