Perl中的相对记录分隔符

时间:2012-01-31 05:08:42

标签: perl parsing data-structures

我的数据如下:

id:40108689 --
chr22_scrambled_bysegments:10762459:F : chr22:17852459:F (1.0),
id:40108116 --
chr22_scrambled_bysegments:25375481:F : chr22_scrambled_bysegments:25375481:F (1.0),
chr22_scrambled_bysegments:25375481:F : chr22:19380919:F (1.0),
id:1 --
chr22:21133765:F : chr22:21133765:F (0.0),

因此每条记录都以id:[somenumber] --

分隔

访问数据的方式是什么,以便我们可以拥有数组的哈希值:

$VAR = { 'id:40108689' => [' chr22_scrambled_bysegments:10762459:F : chr22:17852459:F (1.0),'], 

         'id:40108116' => ['chr22_scrambled_bysegments:25375481:F :chr22_scrambled_bysegments:25375481:F (1.0)',
'chr22_scrambled_bysegments:25375481:F : chr22:19380919:F (1.0),'
         #...etc
       }

我尝试使用记录分隔符来解决这个问题。但不确定如何概括它?

{
    local $/ = " --\n";  # How to include variable content id:[number] ?

    while ($content = <INFILE>) {
      chomp $content;
      print "$content\n" if $content; # Skip empty records
    }
}

1 个答案:

答案 0 :(得分:6)

my $result = {};
my $last_id;
while (my $line = <INFILE>) {
    if ($line =~ /(id:\d+) --/) {
        $last_id = $1;
        next;
    }
    next unless $last_id; # Just in case the file doesn't start with an id line

    push @{ $result->{$last_id} }, $line;
} 

use Data::Dumper;
print Dumper $result;

使用普通记录分隔符。

使用$ last_id来跟踪遇到的最后一个id行,并在遇到另一个id时设置为下一个id。将非id行推送到数组,以获取最后匹配的id行的哈希键。