【问题标题】:Perl script editing a CSV filePerl 脚本编辑 CSV 文件
【发布时间】:2015-04-14 09:42:45
【问题描述】:

我有一个 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];
}

我收到一个错误: 全局符号“@features”需要在 script_T.pl 第 23 行显示包名。

【问题讨论】:

  • 如果你的代码布局更整洁,它会帮助每个人阅读你的代码。这次我已经为你做了。以后请尝试发布更好的东西
  • 嗨 Borodin,我很抱歉,我刚刚学习 Perl,我在编程方面没有什么经验,所以我知道脚本生锈了,但我会改进的。谢谢

标签: arrays perl csv


【解决方案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

【讨论】:

    【解决方案2】:

    在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];
        }
    }
    

    【讨论】:

      【解决方案3】:

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

      Variable Scoping in Perl: the basics

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

      【讨论】:

        猜你喜欢
        • 2022-12-15
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        • 2011-01-22
        • 1970-01-01
        • 2014-05-03
        • 1970-01-01
        • 2019-06-24
        相关资源
        最近更新 更多