【发布时间】:2016-06-09 09:12:47
【问题描述】:
假设您有一个字符串,您知道该字符串至少会匹配一个正则表达式。该正则表达式有两个捕获组,您希望将每对分配给散列中的键值对。
我在想这样的事情,但我不确定这是否是 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
【问题讨论】:
-
回复:“我不确定这 [...] 是否可行”:但您肯定在发帖前尝试过吗?
-
@Bram 哇,你在玩真正的 Perl。我想知道问题限制是否对高代表用户有效......