我對 Perl 還很陌生,正在做一個專案來進一步學習。這是一個小型控制臺文字游戲(翻譯自我的一個 python 專案),部分邏輯需??要從 98 個字符長的池中隨機抽取一個字母。
單獨運行這些函式,我從來沒有遇到過問題,但是當我嘗試將它回圈到一個串列中時,它偶爾會失敗。運行警告告訴我其中一些是未定義的,但我終生無法弄清楚為什么。這是一個 MRE:
package Random;
sub choice {
shift;
my ($str) = @_;
my $random_index = int(rand(length($str)));
return substr($str,$random_index,1); #fixed variable name
}
package Player;
sub new {
my $class = shift;
my $self = { "name" => shift, "letters" => {fillList()} };
bless $self, $class;
return $self;
}
sub drawCharacter {
my $freq = "aaaaaaaaabbccddddeeeeeeeeeeeeffggghhiiiiiiiiijkllllmmnnnnnnooooooooppqrrrrrrssssttttttuuuuvvwwxyyz";
my $choice = Random -> choice($freq);
return $choice;
}
sub fillList {
my @ls = ();
for (0..6) {
push @ls, drawCharacter();
}
return @ls;
}
sub getLetters {
my ($self) = @_;
my $arr = $self -> {letters};
return %$arr;
}
package Main;
my @players = ();
for (0..12){
my $player = Player -> new("Foo");
print($player->getLetters(),"\n");
}
大編輯:添加我正在使用的物件。這可驗證是行不通的。警告:“在列印中使用未初始化的值”和“匿名散列中的奇數個元素”。這就是我認為問題所在。
The list returned by fillList sometimes is missing an item or 2, and in some circumstances even 3 or 4 items are missing. Does anybody know what's going on here? The python one hasn't failed once.
If the python analogue would be helpful, I can include that here too.
uj5u.com熱心網友回復:
該錯誤來自使用哈希參考,您應該有一個陣列參考:
my $self = { "name" => shift, "letters" => {fillList()} };
# ^ ^-- wrong brackets
這就是警告所說的內容:
Odd number of elements in anonymous hash at foo.pl line 22.
您想將其更改為:
my $self = { "name" => shift, "letters" => [fillList()] };
# ^ ^--- creates array ref
還有使用這個陣列的行
return %$arr;
您需要更改%為@.
return @$arr;
在這些修復之后,代碼運行對我來說沒有錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425541.html
