[Oc-pm] looking for a bit of of help using "tr" & while loo
Ben Tilly
btilly at gmail.com
Mon Aug 25 07:00:38 PDT 2008
On Mon, Aug 25, 2008 at 2:09 AM, Raul Ruiz Jr. <fast.linux at yahoo.com> wrote:
> I made a card shuffling program for a school project. It works! I was very
> happy about that :)
>
> However, I'm trying to figure out a way to convert my abbreviated Cards
> (located in @startingdeck) to actual words using a shortcut. I'm trying to
> use "tr" to convert my letters: For example; H now becomes Hearts, or K now
> is displayed as KING and so on. Here is my shuffle code. Can someone help me
> with how I can approach this in my program. I'm trying to use a while loop
> and "tr" to translate the Letters to actual words. I used the following
> loop thats high lighted in blue, and this is not doing what I want:
> Thanks for everyones time.
Unfortunately tr only substitutes letter for letter, so it cannot
change the number of letters. You want to use regular expressions and
the s operator. Like this (untested):
for my $card (@startingdeck) {
$card =~ s/A/Ace/;
$card =~ s/K/King/;
$card =~ s/Q/Queen/;
$card =~ s/J/Jack/;
$card =~ s/D/Diamond/;
$card =~ s/H/Heart/;
$card =~ s/S/Spade/;
$card =~ s/C/Club/;
}
Note that I used mixed case so that, for instance A didn't turn into
ACE which would later turn into ACLUBE when the C was substituted. If
you wish to change that you can then uc all of the cards or else use
the following trick:
my %expanded = (
A => "ACE",
K => "KING",
Q => "QUEEN",
J => "JACK"
D => "DIAMOND",
H => "HEART",
S => "SPADE",
C => "CLUB",
);
# This line assumes no metacharacters, and no key is a piece of another.
my $re = join "|", keys %expanded;
# If those assumptions are wrong, use this version instead:
# my $re = join "|", map quotemeta($_), reverse sort keys %expanded;
for my $card (@startingdeck) {
$card =~ s/$re/$expanded{$1}/g;
}
However note that it is simplest to just start the starting deck off
with what you want:
my @startingdeck;
for my $size ("ACE", 2..10, "JACK", "QUEEN", "KING") {
for my $suit ("HEART", "DIAMOND", "CLUB", "SPADE") {
push @startingdeck, "$size $suit";
}
}
And while I'm giving general advice, use strict. See
http://www.perlmonks.org/index.pl?node=strict.pm for an explanation
why.
Cheers,
Ben
More information about the Oc-pm
mailing list