假设你有一个字符串,你知道它至少会匹配一个正则表达式。该正则表达式有两个捕获组,您希望将每个成对分配给散列中的键值对。
我在考虑这样的事情,但我不确定这是否是 Perl方式 - 或者它是否会起作用。
$string = 'f=banana&c=3;f=strawberry&c=1;f=coconut&c=6';
my %countedfruit;
($countedfruit{$1} = $2) = $string =~ /f=([a-z]+)&c=([0-9]+)/g;
for my $fruit (keys %countedfruit) {
print "The count of '$fruit' is $countedfruit{$fruit}\n";
}
预期结果:
The count of 'banana' is 3
The count of strawberry is 1
The count of coconut is 6
实际结果:
The count of 'coconut' is
答案 0 :(得分:3)
只需使用对列表(匹配)
提供哈希值%countedfruit = $string =~ /f=([a-z]+)&c=([0-9]+)/g;
如果没有偶数编号列表(启用警告),这将发出警告,否则哈希中的键值对由m/
返回的列表中的连续匹配对组成。