Eily, that's a cool hint :-)! Here goes the OOP version (2 files - the module and the script):
# Deck.pm
package Deck;
use 5.014;
use warnings;
use charnames ':full';
use List::Util;
sub new {
my $class = shift;
my $n_cards = 52;
my @suit = (
"\N{BLACK HEART SUIT}",
"\N{BLACK SPADE SUIT}",
"\N{BLACK DIAMOND SUIT}",
"\N{BLACK CLUB SUIT}",
);
my @rank = ((2 .. 10), qw(J Q K A));
my @deck;
my $i = 0;
while (@deck < $n_cards) {
for my $s (@suit) {
for my $r (@rank) {
$deck[$i++] = "$r$s";
}
}
}
return bless \@deck, $class;
}
sub shuffle {
my $deck = shift;
# list context (eg: @shuffled = $deck->shuffle()) will return a n
+ew list
# and leave $deck as is, but scalar or void context (eg: ;
# $deck->shuffle();) will shuffle $deck itself
my $out = wantarray ? [] : $deck;
@$out = List::Util::shuffle(@$deck);
return wantarray ? @$out : $out;
}
sub deal {
my $deck = shift;
my $args = shift;
my $n_cards = $args->{cards} // 5;
my $hands = $args->{hands} // 1;
for (1 .. $hands) {
my @hand;
for (1 .. $n_cards) {
die "no more cards in deck ...\n" unless @$deck;
push @hand, shift @$deck;
}
binmode STDOUT, ':utf8';
say(join " ", @hand);
}
}
1;
# ocards
use 5.014;
use warnings;
use Deck;
use Getopt::Long;
use Pod::Usage;
GetOptions(
"h|?|help" => \( my $help ),
"hands=i" => \( my $hands ),
"cards=i" => \( my $cards ),
) or pod2usage(1);
pod2usage( -exitval => 0, -verbose => 2, -noperldoc => 1 ) if $help;
my $deck = Deck->new();
$deck->shuffle();
$deck->deal({cards => $cards, hands => $hands});
__END__
=head1 NAME
ocards - deal cards from deck of 52 cards (OOP version of cards)
=head1 SYNOPSIS
ocards [options]
options:
-h, -?, --help brief help message
--hands N number of hands to deal [1]
--cards N cards per hand [5]
=cut
EDIT: Fixed my $hands = $args->{hands} instead of my $hands = $args->{cards}. Eily has sharp eyes, huh ... ;-)
The best optimization strategy is to steal from what smarter people have already done. -- brian d foy