使用perl从csv动态输入数组(列)的值的新手



我是perl的新手,需要编写一个具有以下要求的perl脚本:

  1. 需要读取csv文件
  2. 将列存储在阵列中
  3. 假设csv中有7个字段(列):字段1、字段2、字段3、字段4、字段5、字段6、字段7

我需要能够动态地给出任何字段作为输入参数。假设输入参数为字段3、字段7,csv中的数据为:

No of orders'|Date'|Year'|Exp_date'|Month'|time'|Committed
12'|12122002'|2013'|02022012'|12'|1230'|Yes

然后我希望输出为:

Year~Committed                          
2013~Yes 

其余列也采用相同格式:

No of orders~Date~Exp_date~Month~time
12~12122002~02022012~12~1230

目前,我从net获得了一个perl脚本,它只以硬编码的格式为我提供了左侧的结果。但我想在运行时给出输入,并希望生成结果。感谢您的帮助。

$filename = 'xyz.csv';
# use the perl open function to open the file
open(FILE, $filename) or die "Could not read from $filename, program halting.";
# loop through each line in the file
# with the typical "perl file while" loop
while(<FILE>)
{
  chomp;
  # read the fields in the current line into an array
  @fields = split('`|', $_);
 # print the concat
 print "$fields[0]~$fields[1]n";
}

close FILE;

我不会争论是否使用Text::CSV。它与问题无关,split完全可以接受。

以下是我解决问题的方法,假设发布者希望有多行数据的输入文件。

#!/usr/bin/perl -w
# take any file name from the command line, instead of hard coding it
my ($filename) = @ARGV;
my @title;
my @table;
open FILE, "<", $filename or die "Could not read from $filename, program halting.";
while (<FILE>) {
  chomp;
  if (!@title) {
    @title = split ''|';
    next;
  }
  my @row = split ''|';
  # build an array of array references, a two dimensional table
  push @table, @row;
}
close FILE;
print "Access which row? ";
my $row = <STDIN> - 1;
die "Row value is out of range for $filenamen" if (($row < 0) || ($row >= scalar(@table)));
print "Access which column? ";
my $col = <STDIN> - 1;
die "Column value is out of range for $filenamen" if (($col < 0) || ($col >= scalar(@title)));
print "$title[$col]~$table[$row][$col]n";

while循环的第一次传递将把拆分值存储在我们的Title数组中。剩下的过程将逐行附加我们的数据,作为对Table的数组引用。然后,通过一些用户提示和基本的错误检查,我们打印结果。

最新更新