in reply to Re^5: Perl - Unique Numbers
in thread Perl - Unique Numbers

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.