Re: shuffling cards



On 6/28/07, Martin Barth <martin@xxxxxxxxxx> wrote:
snip
> #!/usr/bin/perl

You are missing two lines here.

use strict;
use warnings;

If you don't put those two lines you will be surprised by what Perl
does with your code.

>
> @startingdeck = ("A H","2 H","3 H","4 H","5 H","6 H","7 H","8 H",
> "9 H","10 H","J H","Q H","K H",
> "A D","2 D","3 D","4 D","5 D","6 D","7 D","8 D",
> "9 D","10 D","J D","Q D","K D",
> "A C","2 C","3 C","4 C","5 C","6 C","7 C","8 C",
> "9 C","10 C","J C","Q C","K C",
> "A S","2 S","3 S","4 S","5 S","6 S","7 S","8 S",
> "9 S","10 S","J S","Q S","K S");
>
> for ($x=0;$x<100;$x++){

Don't do this. This is a C style for loop. C style for loops are bad
for a number of reasons I will go into if you ask. Instead use the
Perl style for loop:

for my $x (0 .. 99) {

>
> $shuffle1 = shift(@startingdeck);
> $ahuffle2 = shift(@startingdeck);
> $ahuffle3 = pop(@startingdeck);
> $ahuffle4 = pop(@startingdeck);
>
> push(@startingdeck,$shuffle1,$shuffle3,$shuffle2,$shuffle4);

Remember how I said you would be surprised? Well, here you are
assigning $ahuffle2 and later you are using $shuffle2. Without the
strict pragma Perl thinks this is just fine and uses the empty
variable $shuffle2 even though you meant it to use $affulle2. Also,
never number your variables like this. It is sign you are using the
wrong type of variable. What yo really need is an array:

my @shuffle = shift(@startingdeck), shift(@startingdeck),
pop(@startingdeck), pop(@startingdeck);
push @startingdeck, @shuffle;

> print "@startingdeck\n";
> }
>
> I get it all shuffled up the way I want. I just want now the top five cards
> printed. Which when running this script:
snip

Well, you have a couple options. You could use a slice:

print "@startingdeck[0 .. 4]\n";

You could use indexes:

print "$startingdeck[0] $startingdeck[1] $startingdeck[2]
$startingdeck[3] $startingdeck[4]\n";

You could use a loop

for my $i (0 .. 4) {
print shift $startingdeck;
}
print "\n";

You could flatten the list into a string and take a substr of it

print substr("@startingdeck", 0, 4*5), "\n"; #four characters five times

And a bunch of other ways.
.