我正在尝试在 2 个数组上运行 array_diff。
sub array_diff(\@\@) {
my %e = map { $_ => undef } @{$_[1]};
return @{[
( grep { (exists $e{$_}) ? ( delete $e{$_} ) : ( 1 ) } @{ $_[0] } ),
keys %e
] };
}
my $col = 'col';
my $stg = 'stg';
my @blocks = qw( block1 block2 block3 block4 block5 );
my %hash; @{$hash{$col}{$stg}} = qw( block1 block2 block3 );
my @diff = array_diff(@all_blocks, @{$hash{$col}{$stg}});
print ("diff : @diff\n");
执行上述行时出现以下错误:
Possible unintended interpolation of @diff in string at get_blocks.pl line 56.
Type of arg 2 to main::array_diff must be array (not reference constructor) at get_blocks.pl line 55, near "})"
syntax error at get_blocks.pl line 55, near "})"
Execution of get_blocks.pl aborted due to compilation errors.
但是,当我在没有哈希数组的情况下尝试相同的操作时,它会起作用
my @a = qw( a b c d e);
my @b = qw( c d );
sub array_diff(\@\@) {
my %e = map { $_ => undef } @{$_[1]};
return @{[
( grep { (exists $e{$_}) ? ( delete $e{$_} ) : ( 1 ) } @{ $_[0] } ),
keys %e
] };
}
# symmetric difference
my @diff = array_diff(@a, @b);
print ("diff : @diff\n");
结果:
diff : a b e
最佳答案
可以咨询perldiag找出错误和警告。
Possible unintended interpolation of @diff in string at get_blocks.pl line 56.
(W ambiguous) You said something like '@foo' in a double-quoted string but there was no array @foo in scope at the time. If you wanted a literal @foo, then write it as
\@foo
; otherwise find out what happened to the array you apparently lost track of.
您正在执行“@diff”
,但未声明@diff
。
Type of arg 2 to main::array_diff must be array (not reference constructor) at get_blocks.pl line 55, near "})"
(F) This function requires the argument in that position to be of a certain type. Arrays must be @NAME or @{EXPR} . Hashes must be %NAME or %{EXPR} . No implicit dereferencing is allowed--use the {EXPR} forms as an explicit dereference. See perlref.
正如它所说,\@
原型(prototype)必须采用数组,而不是引用。
# Bad
array_diff([1,2,3], [4,5,6]);
# Good
array_diff(@{[1,2,3]}, @{[4,5,6]});
您的示例代码和您的错误不匹配。 @diff
已声明,并且您已取消引用 $hash{$col}{$stg}
。
我建议不要使用原型(prototype)。它们与用其他语言声明函数的参数不同。相反,它们用于模拟内置函数的神奇行为。
相反,传递引用文献。
my @diff = array_diff(\@all_blocks, $hash{$col}{$stg});
True subroutine signatures不幸的是仍处于实验阶段。
不需要the baby-cart operator @{[]}
围绕grep
。 grep
已经返回一个新数组,无需克隆它。它使代码变得复杂并浪费内存。
关于arrays - 使用 perl array_diff 实用程序比较 2 个数组之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61550719/