使用 Perl 从文件中读取部分

1 arrays perl readline

我正在尝试从 Perl 中的输入文件读取值。输入文件如下所示:

1-sampledata1 This is a sample test
              and data for this continues
2-sampledata2 This is sample test 2
              Data for this also is on second line
Run Code Online (Sandbox Code Playgroud)

我想读取上面的数据,以便数据进入1-sampledata1@array1数据2-sampledata2进入@array2等等。我将有大约 50 个这样的部分。喜欢50-sampledata50

编辑:名称不会总是 X-sampledataX。例如,我刚刚这样做了。所以名称不能循环。我想我必须手动输入它们

到目前为止,我有以下内容(有效)。但我正在寻找一种更有效的方法来做到这一点..

foreach my $line(@body){
        if ($line=~ /^1-sampledata1\s/){
                $line=~ s/1-ENST0000//g;
                $line=~ s/\s+//g;
                push (@array1, $line);
          #using splitarray because i want to store data as one character each
          #for ex: i wana store 'This' as T H I S in different elements of array
                @splitarray1= split ('',$line);
        last if ($line=~ /2-sampledata2/);
        }
}
foreach my $line(@body){
        if ($line=~ /^2-sampledata2\s/){
                $line=~ s/2-ENSBTAP0//g;
                $line=~ s/\s+//g;
                @splitarray2= split ('',$line);
        last if ($line=~ /3-sampledata3/);
        }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,每个部分都有不同的数组,每个部分都有不同的 for 循环。如果我采用到目前为止的方法,那么我最终将得到 50 个 for 循环和 50 个数组。

还有其他更好的方法吗?最后我确实想得到 50 个数组,但不想编写 50 个 for 循环。由于我稍后将在程序中循环遍历 50 个数组,也许将它们存储在一个数组中?我是 Perl 新手,所以它有点令人难以承受......

Sin*_*nür 5

首先要注意的是,您正在尝试使用带有整数后缀的变量名称:不要这样做。每当你发现自己想要这样做时,就使用数组。其次,您只需阅读一次即可浏览文件内容,而不是多次。第三,在 Perl 中通常没有充分的理由将字符串视为字符数组。

更新:此版本的代码使用前导空格的存在来决定要做什么。我也保留以前的版本以供参考。

#!/usr/bin/perl

use strict;
use warnings;

my @data;

while ( my $line = <DATA> ) {
    chomp $line;
    if ( $line =~ s/^ +/ / ) {
        push @{ $data[-1] }, split //, $line;
    }
    else {
        push @data, [ split //, $line ];
    }
}

use Data::Dumper;
print Dumper \@data;

__DATA__
1-sampledata1 This is a sample test
              and data for this continues
2-sampledata2 This is sample test 2
              Data for this also is on second line
Run Code Online (Sandbox Code Playgroud)

以前的版本:

#!/usr/bin/perl

use strict;
use warnings;

my @data;

while ( my $line = <DATA> ) {
    chomp $line;
    $line =~ s/\s+/ /g;
    if ( $line =~ /^[0-9]+-/ ) {
        push @data, [ split //, $line ];
    }
    else {
        push @{ $data[-1] }, split //, $line;
    }
}

use Data::Dumper;
print Dumper \@data;

__DATA__
1-sampledata1 This is a sample test
              and data for this continues
2-sampledata2 This is sample test 2
              Data for this also is on second line
Run Code Online (Sandbox Code Playgroud)