打印数组数组

时间:2016-05-07 02:26:52

标签: arrays perl

我想要三个文件,每个文件包含80行或更多行文本,并打印这三个文件的所有可能组合。

为了清楚起见,我们假设

File1包含

1
2
3

File2包含

4
5
6

File3包含

7
8
9

如果我只打印那些组合,那么我可以使用很多答案。但是,由于文件包含更多行,我谨慎地在Perl脚本中键入。我正在从每个文件构建一个数组,然后我构建这些数组的数组引用。最后,我尝试使用List::Permutor打印组合。

我得到的问题是我打印出内存引用,我无法弄清楚如何取消引用List::Permutor调用中的数组。

Perl代码

use List::Permutor;
use warnings;

open (FILE, app_txt);
chomp (@app = (<FILE>));
close (FILE);

open (FILE, att1_txt);
chomp (@att1 = (<FILE>));
close (FILE);

open (FILE, att2_txt);
chomp (@att2 = (<FILE>));
close (FILE);

my $permutor = List::Permutor->new( \@app, \@att1, \@att2);

while ( my @permutation = $permutor->next() ) {
    print "@permutation\n";
}

3 个答案:

答案 0 :(得分:2)

我为此目的写了Set::CrossProduct

答案 1 :(得分:1)

目前尚不清楚你想要什么。

请注意,以下代码段的所有提供输出均适用于以下输入:

my @app  = ( 1, 2, 3 );
my @att1 = ( 4, 5, 6 );
my @att2 = ( 7, 8, 9 );

如果您想要数组的排列,那么您的代码就可以按原样运行。

use List::Permutor qw( );

my $permutor = List::Permutor->new( \@app, \@att1, \@att2);
while ( my @permutation = $permutor->next() ) {
   say join ", ", map { "[@$_]" } @permutation;
}

输出:

[1 2 3], [4 5 6], [7 8 9]
[1 2 3], [7 8 9], [4 5 6]
[4 5 6], [1 2 3], [7 8 9]
[4 5 6], [7 8 9], [1 2 3]
[7 8 9], [1 2 3], [4 5 6]
[7 8 9], [4 5 6], [1 2 3]

如果你想要数组内容的排列(无论字符串来自哪个数组),那么你只需要从数组的内容创建一个列表。

use List::Permutor qw( );

my $permutor = List::Permutor->new( @app, @att1, @att2 );
while ( my @permutation = $permutor->next() ) {
   say "@permutation";
}

输出:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 9 8
1 2 3 4 5 6 8 7 9
1 2 3 4 5 6 8 9 7
1 2 3 4 5 6 9 7 8
1 2 3 4 5 6 9 8 7
1 2 3 4 5 7 6 8 9
1 2 3 4 5 7 6 9 8
1 2 3 4 5 7 8 6 9
1 2 3 4 5 7 8 9 6
...
9 8 7 6 5 4 3 2 1

请记住,P(80)是可观测宇宙中原子数的100,000,000,000,000,000,000,000,000,000,000,000,000,000倍。

如果您想要每个阵列中所有可能的单个元素集,那么您可以使用以下内容:

for my $app (@app) {
for my $att1 (@att1) {
for my $att2 (@att2) {
   say "$app $att1 $att2";
}}}

use Algorithm::Loops qw( NestedLoops );

my $iter = NestedLoops([ \@app, \@att1, \@att2 ]);
while ( my ($app, $att1, $att2) = $iter->() ) {
   say "$app $att1 $att2";
}

输出:

1 4 7
1 4 8
1 4 9
1 5 7
1 5 8
1 5 9
1 6 7
1 6 8
1 6 9
2 4 7
...
3 6 9

答案 2 :(得分:0)

我通过作弊解决了格式化的最后一个问题。我刚编辑了源文件并删除了所有的\ r和\ n。

最终代码:

use Algorithm::Loops qw( NestedLoops );
use warnings;

open (FILE, app_txt);
 ($app = (<FILE>));
close (FILE);
my @app = split /,/, $app;

open (FILE, att1_txt);
 ($att1 = (<FILE>));
close (FILE);
my @att1 = split /,/, $att1;

open (FILE, att2_txt);
 ($att2 = (<FILE>));
close (FILE);
my @att2= split /,/, $att2;

my $iter = NestedLoops([ \@app, \@att1, \@att2 ]);
while ( my ($app, $att1, $att2) = $iter->() ) {
    open (my $fh, '>', 'test');
    print  $fh "$app $att1 $att2\n";
    close $fh;
}

print "done\n";