在perl中匹配2个数组相同位置的元素
我有 2 个数组,
@a = qw/ A B C D E /; @b = qw/ B B C A /;
我需要检查相同的元素是否出现在每个数组的相同位置,
e.g. $a[2] = "B"; $b[3] = "C";
如果是的话,计算发生这种情况的次数 它需要忽略任何空白元素
e.g. $a[6] = ; $b[6] = ;
注释是最受赞赏的我喜欢理解脚本。
我尝试了 intersect eq == cmp 等,但我不太明白并且不太确定
提前致谢。
到目前为止,这是我的代码:
#!/usr/bin/perl -w
my @a = <FILE1>;
my @b = <FILE2>;
$occurs = 0; #Using eq
foreach my $letter (@a) {
if (my $letter2 (@a) eq $letter) { #Syntax error here
$count ++;
}
} #syntax error here
I have 2 arrays
@a = qw/ A B C D E /; @b = qw/ B B C A /;
I need to check if the same element appear in the same position of each array
e.g. $a[2] = "B"; $b[3] = "C";
if so count the number of times this happened
it need to disregard any blank elements
e.g. $a[6] = ; $b[6] = ;
comments are most appreciated I like to understand the script.
I tried intersect eq == cmp etc but I can't quite get it and not quite sure
Thanks in advance.
Here's my code so far:
#!/usr/bin/perl -w
my @a = <FILE1>;
my @b = <FILE2>;
$occurs = 0; #Using eq
foreach my $letter (@a) {
if (my $letter2 (@a) eq $letter) { #Syntax error here
$count ++;
}
} #syntax error here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于您所述的问题,我会使用如下内容:
要忽略空元素,您可以检查
define($a[$_])
和length($a[$_ ])
也是如此。然而,
与
qw/BBCA/
相同,因此不引入空元素。此外,您的相同元素示例在不同位置显示了不同元素。For your problem as stated, I'd use something like this:
To disregard empty elements, you can check for
defined($a[$_])
andlength($a[$_])
as well.However,
is the same as
qw/B B C A/
, so no empty elements are introduced. Also, your example for the same element shows different elements at different positions.这里需要澄清空白的定义。是空字符串吗?未定义的值?空白?
我假设任何没有非空白字符的元素在下面的示例中为 blank,该示例显示了如何使用
each @array
构造来完成此操作:The definition of blank here needs to be clarified. Is it an empty string? An
undef
ined value? Whitespace?I'm assuming any element with no non-whitespace characters as blank in the example below, which shows how it could be done with the
each @array
construct: