More as a general point about this class of problem, it's my turn to repeat the well-worn advice about "whenever you start finding yourself with variables ending with incremental numbers, it's time to use arrays instead."
There's nothing at all wrong with assigning an array to a grep'ed version of itself, any more than there is map'ing one - you really don't need @cards1, @cards2 etc.
As Zaxo said, shuffling and popping would be better here, but should you wish to do this (or similar) "in place" as you are doing, something like this would be easier...
while (@hand < $num_to_deal) {
return "no more cards" unless @cards;
push @hand,$cards[int(rand(@cards))];
@cards = grep{$_ ne $hand[$#hand]}@cards;
}
NB - I'm not
advocating this code - as others have said, the grep is nasty - just pointing out a principle :)
Cheers, Ben.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.