如何通过将每行拆分为新行来从输入文件中对2D数组进行种子处理

时间:2017-09-06 10:08:41

标签: perl

我有一个像这样的输入文件,它看起来像一个矩阵

              55 ;           3 ;          21 ;    1 ; 0 ; 0 ; 46
             105 ;           8 ;          21 ;    2 ; 0 ; 0 ; 52
             155 ;          13 ;          21 ;    3 ; 0 ; 0 ; 32
             205 ;          18 ;          21 ;    4 ; 0 ; 0 ; 60
             255 ;          23 ;          21 ;    5 ; 0 ; 0 ; 19
             305 ;          28 ;          21 ;    6 ; 0 ; 0 ; 48

如何阅读文件以拆分由';'分隔的每一行?进入我的多维数组的新行?

for ($i = 0; $i < 64; $i++)  {
    open (FH, "E:/Wessam/Research Group/comparisons/64 PEs/log files/Injector_Log_$i.txt");
    while(<FH>)  {
        @var[$j] = $_;
        $j++;
    }
    close (FH);
}

然而,每当我打印$ var [0]或$ var [1]时,它只显示64个日志文件之一的最后一行,无论如何我可以有一个多维数组吗?

1 个答案:

答案 0 :(得分:1)

对您的代码的一些评论:

# Professional Perl programmers rarely use this
# "C-style" for loop. Use foreach instead.
for ($i = 0; $i < 64; $i++)  {
    # Please use three-arg open() and lexical filehandles.
    # Always check the return value from open().
    open (FH, "E:/Wessam/Research Group/comparisons/64 PEs/log files/Injector_Log_$i.txt");
    while(<FH>)  {
        # This should be $var[$j].
        # But it's better written using push().
        # And you're not splitting your data.
        @var[$j] = $_;
        $j++;
    }
    close (FH);
}

我会这样写:

my $dir = 'E:/Wessam/Research Group/comparisons/64 PEs/log files';
my @data;
foreach my $i (0 .. 63) {
   my $file = "$dir/Injector_Log_$i.txt";
   open my $log_fh, '<', $file or die "Can't open $file: $!";

   while (<$log_fh>) {
     # Match sequences of digits - \d+
     # Capture those matches - (...)
     # Find *all* matches - /g
     # Create an anonymous array = [ ... ]
     # Push a reference to that array onto @data
     push @data, [ /(\d+)/g ];
   }

   # No need to explicitly close the filehandle, as it
   # is automatically closed when $log_fh goes out of scope.
}

另外,我猜你的代码不包含use strictuse warnings。你应该总是使用这些。