[英]Compare multiple columns from a single file an count the occurrence of a value in these columns
[英]Is there a way to assign columns from a file to multiple arrays?
我有一个名为data.txt的文件,看起来像这样:
12487 72 3.179
12487 84 2.47
12976 82 3.22
12443 81 4.29
我需要做的是将每个列从文件中读取时放在其自己的数组中,这样就可以了:
@a = 12487 12487 12976 12443
@b = 72 84 82 81
@c = 3.179 2.47 3.22 4.29
因此,每一行都将执行类似$ 1进入@a $ 2进入@b $ 3进入@c的操作-但我不确定如何确切地执行此操作。
我首先尝试从每一行中获取每个数组索引,但是这太多了,无法进行排序(文件很大)。 我对perl还是很陌生,所以我很困惑,不确定我应该在perldoc中寻找什么(这是我用作入门参考)。
使用push将元素附加到数组。
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
my (@a, @b, @c);
while (<>) {
my @columns = split;
push @a, $columns[0];
push @b, $columns[1];
push @c, $columns[2];
}
say "@$_" for \@a, \@b, \@c;
除了三下推,您还可以使用
push @{ (\@a, \@b, \@c)[$_] }, $columns[$_] for 0 .. 2;
但我觉得它不可读。 它遍历要同时添加到的列和数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.