1

我是 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;
4

1 回答 1

0

I am not going to argue whether to use Text::CSV or not. It is not relevant to the question and split is perfectly acceptable.

Here is how I would solve the problem, assuming that the poster wants to have input files of more than one line of data.

#!/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 $filename\n" if (($row < 0) || ($row >= scalar(@table)));

print "Access which column? ";
my $col = <STDIN> - 1;
die "Column value is out of range for $filename\n" if (($col < 0) || ($col >= scalar(@title)));

print "$title[$col]\~$table[$row][$col]\n";

The first pass of the while loop will store the split values in our Title array. The remaining passes will append our data, row by row, as array references to Table. Then with some user prompting and basic error checking, we print our results.

于 2013-07-28T05:37:27.910 回答