arrays - 使用 perl array_diff 实用程序比较 2 个数组之间的差异

标签 arrays perl hash diff array-difference

我正在尝试在 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 @{[]}围绕grepgrep 已经返回一个新数组,无需克隆它。它使代码变得复杂并浪费内存。

关于arrays - 使用 perl array_diff 实用程序比较 2 个数组之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61550719/

相关文章:

perl - 如何从 Perl 中的散列数组创建散列散列?

java - 如何使我的线性探针哈希函数更高效?

c++ - 数组、 vector 和链表

c - Perl、C、XS - 解压 float 组

perl - 如何规范化 Perl 中的路径? (不检查文件系统)

c++ - 如何减少哈希表槽中的指针/地址宽度?

python - 如何处理要在 cron 作业中处理的新文件

java - 如何错误处理数组中重复的学生 ID

python - 限制 Python 中数组/列表中输入值的数量

php - 将mysql中的值写入php数组