Perl - 用数值替换数组字符串

时间:2013-12-06 06:49:32

标签: arrays perl

作为学习perl的练习,我决定写一个简单的二十一点游戏。我正在使用数组作为卡值。我希望能够在玩家卡列表中包含插孔,国王和皇后卡但是我也希望能够使用这些卡添加到21.首先想到我尝试使用变量然而这似乎不起作用

数组:@cards = (1,2,3,4,5,6,7,8,9,10,$ace ='ace',$jack ='jack', $queen ='queen', $king ='king'); #NOTE: Ace is 11 or 1

    sub PrintPlayersCards
{
    $playerTotal = 0;
    print "PLAYERS CARDS:@playerCurCards\n";
    @cards[$jack] = 10;
    @cards[$queen] = 10;
    @cards[$king] = 10;
    grep {$playerTotal += $_} @playerCurCards;
    print "Your total is :$playerTotal\n";
    @cards[$king] = "King";
    @cards[$queen] = "queen";
    @cards[$jack] = "jack";
}

@playerCurCards是一个存储球员牌的阵列。 EG:从一开始就是3,从击中等国王。

1 个答案:

答案 0 :(得分:2)

您可以将其存储在哈希中:

#!/usr/bin/perl

use strict;
use warnings;


my %cards = ('1'=> '1',
    '2' => '2',
    '3' => '3',
    '4' => '4',
    '5' => '5',
    '6' => '6',
    '7' => '7',
    '8' => '8',
    '9' => '9',
    '10' => '10',
    'jack' => '10',
    'king' => '10',
    'queen' => '10',
);

sub PrintPlayersCards {
    my $playerTotal = 0;
    my @hand = @_;
    print "PLAYERS CARD:\n";
    print "\t$_\n" foreach @hand;
    grep {$playerTotal += $cards{$_}} @hand;
    print "Your total is: $playerTotal\n";
}

#this is just to test it
my @playerCurCards = ('1', 'queen', 'king');
PrintPlayersCards(@playerCurCards);