Howdy, welcome to the Monastery!

There's many ways that this could be done. For one, you could check the "candidate" in your loop and get another one from rand if you already saw it before. In the following code, I'm using a hash (associative array) to remember which numbers were already seen:

my $x = 1; my $y = 20; my $looptimes = 10; my %numbers = (); foreach(1 .. $looptimes) { my $candidate = -1; do { $candidate = int(rand ($y - $x + 1)) + $x; } while(exists $numbers{$candidate}); $numbers{$candidate} = 1; } say join ",", keys %numbers;

If you only care about the result, you could also e.g. take the list of numbers from $x to $y, shuffle it, and then grab the $looptimes numbers. How do I shuffle an array? has more on shuffling arrays; the executive summary is that there's a shuffle function in List::Util (a core module):

use List::Util qw/shuffle/; my $x = 1; my $y = 20; my $looptimes = 10; my @numbers = shuffle($x .. $y); say join ",", @numbers[0 .. ($looptimes - 1)];

Though that said I reckon you care more about the "how" than the result.

Since you're starting out, here's a few general suggestions, too.

Hope this helps!


In reply to Re: Perl - Unique Numbers by AppleFritter
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.