Perl脚本编辑CSV文件

时间:2015-04-14 09:42:45

标签: arrays perl csv

我有一个CSV输入文件(input.csv),其数字如下:

1.34,7.56,4.57,6.7,4.9, 3.4,5.7,5.4,........

我想编辑文件并在字段之间插入数字和冒号,如;

1:1.34 2:7.56 3:4.57 4:6.7 5:4.9 6:3.4 7:5.7 8:5.4..........

这是我的剧本:

#!/usr/bin/perl
use strict;
use warnings;

#Opening the CSV file

my $csv_file = "input.csv";

open (my $fh, "<", $csv_file) or die "Cannot open '$csv_file': $! ";

#parsing

while (my $lines = <$fh> ) {

  chomp $lines;

  my @features = split (',', $lines);
  print "$lines \n";
} 

#inserting numbers

for ( my $x = 1; $x <= 1371; $x++ ){
  print $x . ":" . $features[$x-1];
}

我收到错误:     全球符号&#34; @ features&#34;需要在script_T.pl第23行显式包名。

3 个答案:

答案 0 :(得分:1)

这可以通过splitmapjoin整齐地完成,就像这样。

#!/usr/bin/perl
use strict;
use warnings;

while ( <> ) {
  my @fields = split /\s*,\s*/;
  print join ' ', map "$_:$fields[$_-1]", 1 .. @fields;
}

<强>输出

1:1.34 2:7.56 3:4.57 4:6.7 5:4.9 6:3.4 7:5.7 8:5.4 9:........

程序期望输入文件的路径作为命令行上的参数,如此

./count_fields.pl input.csv

答案 1 :(得分:0)

在while循环之前定义@features

my @features;
while (my $lines = <$fh> ) {
    chomp $lines;
    @features = split (',', $lines);
    print "$lines \n";

    for(my $x=1; $x <=1371 ; $x++){
        print $x .":".$features[$x-1];
    }
}

答案 2 :(得分:-1)

您已使用“my”在while块中声明了@features数组,这使得它仅在块中可用。在之前宣布它。 要了解有关perl范围的更多信息,请阅读

Variable Scoping in Perl: the basics

what-is-the-difference-between-my-and-our-in-perl

相关问题