Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-03-28 17:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found