in reply to Nested foreach loops

Hey guys thanks for your help, after many hours of toil, I seem to have worked it out. I did all this BEFORE reading Marshall's reply. Feeling quite happy with myself for finally getting it to work :). Could I have some opinions on the way I went about it? Should I have done anything differently/more efficiently?

#!/usr/bin/perl -w OUTER: @suit=('spades', 'hearts', 'clubs', 'diamonds'); foreach $suit(@suit) { INNER: @types=( "ace","2","3","4","5","6","7","8","9","10","jack"," +queen","king"); foreach $types(@types) { $card="$types of $suit"; print "$card\n"; $cardcounter++; push(@cards,$card,); } } print "\n"x2; print "$cardcounter cards have been created\n"; print "\n"x2; ATTEMPT: for ($counter=1;$counter<11;) { $i = int(rand(@cards)) ; push (@alreadyused,@cards[$i]); $count=grep (/@cards[$i]/i,@alreadyused); if ($count<2) { print "Random card is: @cards[$i]\n"; $counter++; push (@iterations,@cards[$i]); } else {next ATTEMPT;} } print "\n"x2; $number=@iterations; print "$number random cards have been chosen, with no duplicates";

Replies are listed 'Best First'.
Re^2: Nested foreach loops
by toolic (Bishop) on Feb 28, 2011 at 17:12 UTC
    • Fix these warnings:
      Scalar value @cards[$i] better written as $cards[$i] at
    • Add use strict; then declare all variables with my. See use strict and warnings.
    • Perl has a convenient quoting operator which is handy for constructing lists: qw. It saves you from excessive quotes and commas. Range Operators are nice too:
      foreach $types ( qw(ace jack queen king), (2 .. 10) ) {
    • perltidy is useful for indenting code.