prasadbabu,
I think you have misunderstood though it is not your fault and I might be the one that is wrong. rsriram said unique elements but meant unique indices judging by the rest of the node. In other words, by repeating the random number selection, the same index was appearing multiple times. While your updated use of the Data::Random module gets the job done, the %unique is not needed. Update: Your second update corrects all the problems and this is a valid solution.

Several ways to do this that involve changing the original array are to use List::Util's shuffle() as davorg has suggested or use splice to pull out elements randomly. Alternatively, a parrallel array of indices allows the original array to remain intact.

my (@index, @rand); @index = 0 .. $#array; push @rand, splice(@index, rand @index, 1) for 1 .. 10; print "@array[@rand]\n"; # untested

Update: I added a couple of alternatives that do not leave the original array intact. Additionally, I need to point out that your use of Data::Random can be terribly runtime inefficient. See my update in this node for details. The alternatives consume more memory (trading space for time). I also originally incorrectly thought that the module was returning the set in the original order by default but it isn't.

Cheers - L~R


In reply to Re^2: Picking unique element in random from a array by Limbic~Region
in thread Picking unique element in random from a array by rsriram

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.