我希望根据从 CSV 文件中提取的数据填充多个数组。
现在在我的脚本中,我逐行读取文件并取出我需要的每一列并将其放入一个单独的数组中(例如,服务器主机名放入@server数组,容量信息放入@容量数组等)
填充数组后,我使用简单的 for 循环将它们打印出来,例如
for (my $i = 0; $i < @server; $i++)
{
#print different arrays by using $i for the key
}
目前这是可行的,因为在我将所有信息存储到数组中的循环中,它是线性完成的,因此每个数组索引与其他数组中的信息匹配。
但是,我现在需要按服务器对 @server 数组中的信息进行排序。我想做的是按字母顺序对 @server 数组进行排序,但让其他数组中(排序之前)匹配的每个索引也进行相同的排序。
我已经尝试解决这个问题有一段时间了,在哈希和多维数组之间进行切换,再加上我对 Perl 相对较新,这对我来说变得非常困难。
下面是我用来从 CSV 文件中提取信息的代码。我知道 Text::CSV 模块,但是我无法安装其他模块。
while (my $line = <INFILE>)
{
chomp($line);
if (index($line, "ONSITE") == -1 && index($line, "IBM3584") != -1)
my @separated = split(',', $line);
if ($separated[4] > 0)
{
push (@server, $separated[0]);
push (@slot, $separated[7]);
push (@volume, $separated[1]);
push (@used, $separated[8]);
push (@pool, $separated[3]);
}
}
最佳答案
如果您想保持数据结构不变,可以按索引排序
use strict;
use warnings;
my (@fruit, @line, @color);
while (<DATA>) {
chomp;
my @cols = split ',';
push @fruit, $cols[0];
push @line, $cols[1];
push @color, $cols[2];
}
for my $index (sort {$fruit[$a] cmp $fruit[$b]} (0..$#fruit)) {
printf "%-12s %-8s %s\n", $fruit[$index], $line[$index], $color[$index];
}
__DATA__
apple,line 1,red
orange,line 2,orange
pear,line 3,green
strawberry,line 4,red
banana,line 5,yellow
kiwi,line 6,greyish green
输出:
apple line 1 red
banana line 5 yellow
kiwi line 6 greyish green
orange line 2 orange
pear line 3 green
strawberry line 4 red
但是,如果将数据分组在一起有意义,我建议使用哈希数组:
my @records;
while (<DATA>) {
chomp;
my @cols = split ',';
push @records, {
fruit => $col[0],
line => $col[1],
color => $col[2],
};
}
for my $record (sort {$a->{fruit} cmp $b->{fruit}} @records) {
printf "%-12s %-8s %s\n", @{$record}{qw(fruit line color)};
}
关于arrays - 需要根据单独数组的排序对4个不同的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25209964/