1

我已将值存储在 5 个文本文件中。每个文本文件中的值应被视为一个数组。我正在尝试编写一个 perl 程序来读取和打印这 5 个数组中的公共元素。

例如

@a1=(1,7,4,5); 

@a2=(1,9,4,5); 

@a3=qw(1,6,4,5 ); 

@a4=qw(1 2 4 5 ); 

@a5=qw(1 2 4 5 ); 

我希望打印

1 4 5 
4

2 回答 2

1

The perlfaq has lots of answer to questions that are frequently asked. Of course it's all a bit of a waste of time and effort if no-one bothers to check there before asking the question again :-)

How do I compute the difference of two arrays? How do I compute the intersection of two arrays?

Use a hash. Here's code to do both and more. It assumes that each element is unique in a given array:

my (@union, @intersection, @difference);
my %count = ();
foreach my $element (@array1, @array2) { $count{$element}++ }
foreach my $element (keys %count) {
    push @union, $element;
    push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}

You need the intersection of two arrays. And then do it three more times.

于 2012-07-26T10:02:39.663 回答
1

你没有说你的输入文件有什么格式,但是这个程序会找到每个文件中的所有数字字符串,并列出所有这些数字字符串的共同值。

输入文件列表应为命令行参数。

use strict;
use warnings;

use File::Slurp 'read_file';

my %counts;

for (@ARGV) {
  $counts{$_}++ for map /\d+/g, read_file $_;
}

my @common = grep $counts{$_} == @ARGV, keys %counts;

printf "(%s)\n", join ', ', @common;

输出

(4, 1, 5)
于 2012-07-26T08:54:07.027 回答