in reply to Nested foreach loops
The basic operations for dealing with arrays are: push, pop, shift, unshift and splice. Review how each one of these work. Also you can access each element in the array individually by using an index. $deck [ 0 ] is the first card.
You will have to pick a card at random from the deck. Read about the rand() function rand() function. The deck has the scalar value of "@deck" number of cards in it. The indicies of all the cards are [ 0..@deck-1]. Note this range starts at zero not one!
Once you can pick a card at random from the deck and print it, you have to figure out how you will satisfy the requirement that you can't have duplicates. I mean there is only one "2 of clubs" so you have to figure out a way to prevent it being picked twice. suggestion: think about what splice does.
Have fun and let us know how it goes! Everybody here was a beginner once.
#!/usr/bin/perl -w use strict; my @deck; foreach my $suit qw(clubs diamonds hearts spades) { #print "Working on the $suit\n"; # un-comment to watch looping foreach my $card_type (2..10,'ace','king','queen','jack') { #print " Now card=$card_type\n"; # un-comment to watch loop push @deck, "$card_type of $suit"; } } print "There are ".@deck." cards in the deck\n"; foreach my $card (@deck) { print "$card\n"; } __END__ Output....uncomment the 2 print statements in the nested loop to see exactly how the looping is done... There are 52 cards in the deck 2 of clubs 3 of clubs 4 of clubs ... etc. then diamonds, then hearts, spades...
|
|---|