gpt4 book ai didi

perl - 为什么在取消引用左侧的 arrayref 时 smartmatch 不起作用?

转载 作者:行者123 更新时间:2023-12-04 18:15:29 26 4
gpt4 key购买 nike

我目前正在阅读Intermediate Perl来自 O'Reilly,我正在尝试做其中一项练习。我对 Perl 中的引用不熟悉,所以我希望我不会误解某些东西并错误地编写此练习。

但是,我尝试调试此代码,但无法得出智能匹配行每次都失败的结论。据我了解@array ~~ $scalar如果在 @array 中找到按字符串的标量值,则应返回 true .

下面是我的代码:

#!/usr/bin/perl -w
use 5.010;

my @rick = qw(shirt shotgun knife crossbow water);
my @shane = qw(ball jumprope thumbtacks crossbow water);
my @dale = qw(notebook shotgun pistol pocketprotector);
my %all = (
Rick => \@rick,
Shane => \@shane,
Dale => \@dale,
);

check_items_for_all(\%all);

sub check_items_for_all {
my $all = shift;
foreach $person (keys %$all) {
#print("$person\n");
$items = $all->{$person};
#print("@$items");
check_required_items($person, $items);
}
}

sub check_required_items {
my $who = shift; #persons name
my $items = shift; #reference to items array
my @required = qw(water crossbow);
print(
"Analyzing $who who has the following items: @$items. Item being compared is $item \n"
);
foreach $item (@required) {
unless (@$items ~~ $item) {
print "Item $item not found on $who!\n";
}
}
}

最佳答案

如果您反转匹配,它将起作用:

$item ~~ @$items

或者
$item ~~ $items  # Smart-matching works with references too.

PS:习惯加 use strict;到你的程序的开始。它会指出你的代码中的一些错误:)

关于perl - 为什么在取消引用左侧的 arrayref 时 smartmatch 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11833756/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com