Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 编辑CSV文件的Perl脚本_Arrays_Perl_Csv - Fatal编程技术网

Arrays 编辑CSV文件的Perl脚本

Arrays 编辑CSV文件的Perl脚本,arrays,perl,csv,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 =

我有一个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];
}
#/usr/bin/perl
严格使用;
使用警告;
#打开CSV文件
my$csv_file=“input.csv”;

在while循环之前打开(my$fh),定义
@功能

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];
    }
}
my@功能;
while(我的$line=){
咀嚼$line;
@特征=拆分(“,”,$行);
打印“$lines\n”;

对于(my$x=1;$x您已使用“my”在while块内声明@features数组,这使得它仅在块内可用。请在while之前声明它。 要了解有关perl中作用域的更多信息,请阅读


这可以通过
split
map
join
巧妙地完成,如下所示

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

while ( <> ) {
  my @fields = split /\s*,\s*/;
  print join ' ', map "$_:$fields[$_-1]", 1 .. @fields;
}
程序希望输入文件的路径作为命令行上的参数,如下所示

./count_fields.pl input.csv

如果你把你的代码放得更整齐一些,这将有助于每个人阅读你的代码。我这次为你做了。以后请尝试发布一些nicerHi Borodin的文章,我很抱歉,我只是在学习Perl,我在编程方面没有什么经验,所以我知道脚本已经生锈了,但我会改进的。谢谢
./count_fields.pl input.csv