【问题标题】:Relative Record Separator in PerlPerl 中的相对记录分隔符
【发布时间】:2012-01-31 13:32:20
【问题描述】:

我的数据如下所示:

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
    }
}

【问题讨论】:

    标签: perl parsing data-structures


    【解决方案1】:
    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 行的哈希键的数组中。

    【讨论】:

    • 谢谢。但是,我认为你需要这个小修正:if ( $line !~ /id:\d+ --/ ) { push @{ $result-&gt;{$last_id} }, $line; }
    猜你喜欢
    • 2019-04-22
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    相关资源
    最近更新 更多