我有一个数组@test.检查数组的每个元素是否是相同的字符串的最佳方式是什么?
我知道我可以用foreach循环来做,但是有没有更好的方法呢?我检查了地图功能,但我不知道这是我需要的.
解决方法
如果字符串已知,则可以在标量上下文中使用
grep:
if (@test == grep { $_ eq $string } @test) {
# all equal
}
否则,使用哈希:
my %string = map { $_,1 } @test;
if (keys %string == 1) {
# all equal
}
或更短的版本:
if (keys %{{ map {$_,1} @test }} == 1) {
# all equal
}
注意:当用作Perl中的字符串时,未定义的值的行为类似于空字符串(“”).因此,如果数组只包含空字符串和undefs,则检查将返回true.
这里有一个解决方案:
my $is_equal = 0;
my $string = $test[0]; # the first element
for my $i (0..$#test) {
last unless defined $string == defined $test[$i];
last if defined $test[$i] && $test[$i] ne $string;
$is_equal = 1 if $i == $#test;
}