I guess that you have code that works to your satisfaction. But I thought I'd point this out if you haven't realized it yet.... A Perl 2D structure is very similar to a dynamically built 2D structure in C (not what the compiler does for a static 2D declaration).
In C I would malloc an array of pointers (the number of rows), then for each row, malloc an array for the data and set the row pointer for that row to point to that array of data. Perl works the same way. @cards is an array of pointers to array.
You can use the $card[$i][$j] syntax just like in C, card[i][j]. There is no need here to be "popping" anything. You have a mix of Perl ideas with C ideas and this combination creates some confusing code!
As you write more Perl code, you will find that C style "for" loops are rare. The dreaded "off by one error", which statistically is there most common programming error by many studies, is much less likely in Perl because under most circumstances you don't have to explicitly specify array index bounds like in C. This is a major advantage to Perl.
There is other "magic" in Perl, for example, the core module Data::Dumper which can dump any data structure of arbitrary complexity - there is no equivalent in C.
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
my @deck = deck_maker();
print Dumper \@deck;
sub deck_maker {
my @deck = (); #the deck for returning
my @types = ('spades', 'hearts', 'diamonds', 'clubs');
my @cards = (
[2,3,4,5,6,7,8,9,10,'J','Q','K','A'],
[2,3,4,5,6,7,8,9,10,'J','Q','K','A'],
[2,3,4,5,6,7,8,9,10,'J','Q','K','A'],
[2,3,4,5,6,7,8,9,10,'J','Q','K','A']
);
for ( my $i=0; $i < 4; $i++) {
for ( my $j=0; $j < 13; $j++) {
my $newcard = "$cards[$i][$j] of $types[$i]";#####
push(@deck, $newcard);
}
}
return @deck; #return the new deck
}
As previously mentioned, I wouldn't write the code this way, but for example, this is possible:
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
my @deck = deck_maker();
print Dumper \@deck;
sub deck_maker {
my @deck = (); #the deck for returning
my @types = ('spades', 'hearts', 'diamonds', 'clubs');
for ( my $i=0; $i < 4; $i++)
{
my @cards = ( 2,3,4,5,6,7,8,9,10,'J','Q','K','A');
while (my $card = pop @cards)
{
my $newcard = "$card of $types[$i]";
push(@deck, $newcard);
}
}
return @deck; #return the new deck
}
Every time Perl sees "my", you get a "new" one. Perl will re-use the same memory if it can. The syntax that you wound up with generates a run-time error. Why get more complicated than necessary? No need to use a multidimensional structure when a 1D structure will work. Note that in my "while" loop, I don't have to know how many cards are there. |