Again, take a closer look at his code.

His loop is not equivalent to for (1 .. 10). Rewriting his loop in a more "conventional" way, it's equivalent to:

while (keys %numbers < 10) { my $num = int( rand 20 ) + 1; $numbers{$num}++; }
It will loop until there are 10 keys in %numbers, which means that 10 distinct numbers have been chosen, since hashes can't have duplicate keys.

Where do you see that he saves anything?

Because the value associated with the key is incremented each time that value is chosen, the keys will "save" the list of distinct numbers chosen, while the values will "save" the number of times each one came up.

His loop handling is definitely non-Perl.

I think we'll just have to disagree on that one. I find

$numbers{int(rand(20))+1}++ while keys %numbers < 10;
to be far more idiomatically Perlish than the "conventional" equivalent I provided above.

P.S. You seem to have gotten your attributions crossed. I'm not deelinux.


In reply to Re^6: Perl - Unique Numbers by dsheroh
in thread Perl - Unique Numbers by deelinux

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.