【问题标题】:Perl: Combine duplicated keys in Hash of ArrayPerl:在数组的哈希中组合重复的键
【发布时间】:2020-10-23 15:18:39
【问题描述】:

我对此有疑问,想知道是否有人可以提供帮助。我正在解析一个 .txt 文件,并且想要组合重复的键和它的值。本质上,对于每个标识符,我想存储它的高度值。每个“样本”有 2 个条目(A 和 B)。我的文件是这样存储的:

while(...){
    @data= split ("\t", $line);  
                            
    $curr_identifier= $data[0];
    $markername= $data[1];
    $position1= $data[2];
    $height= $data[4];

    if ($line >0){
         $result[0] = $markername;
         $result[1] = $position1;
         $result[2] = $height;
         $result[3] = $curr_identifier;

         $data{$curr_identifier}= [@result];
     }
}

这似乎工作正常,但我的问题是当我将此数据发送到下面的函数时。它打印 $curr_identifier 两次。我只想填充唯一标识符并检查它的 $height 变量是否存在。

 if (!defined $data{$curr_identifier}[2]){
            $output1= "no height for both markers- failed";
 } else {
    if ($data{$curr_identifier}[2] eq " ") {
        $output1 = $markername;

    } 
 }
 
 print $curr_identifier, $output1 . "\t" . $output1 . "\n";

基本上,如果两个标记 (A&B) 的样本高度都存在,那么输出就是两个标记。

'1', 'A', 'B'

如果高度不存在,则报告标记的输出为空。

'2', 'A', ' '

'3', ' ', 'B'

我当前的输出是这样打印出来的:

1, A
1, B

2, A
2, ' '

3, ' '
3, B'


_DATA_
Name Marker Position1 Height Time
1   A   A       6246        0.9706
1   B   B       3237        0.9706
2   A                   0
2   B   B       5495        0.9775
3   A   A       11254       0.9694
3   B                       0

【问题讨论】:

  • 需要minimal reproducible example,而不是随机不完整的sn-ps代码。
  • 第一个 sn-p 显示我如何将文件数据存储到 %data 哈希中,第二个 sn-p 是我在 while 循环中调用的子例程。目的是只输出哈希数据。
  • == " " 没有意义; == 是数字比较,对于字符串比较使用eq。它真的是一个空格,而不是一个空字符串吗?
  • 这是一个空字符串。当数据文件中缺少高度变量时,它将为空。

标签: sql perl intellij-idea hash key-value


【解决方案1】:

您想要的输出基本上可以归结为这几行 perl 代码:

while (<DATA>) {
  ($name,$mark,$pos,$heig,$time) = split /\t/;
  print "'$name','$mark','$pos'\n";
}

__DATA__
... your tab-separated data here ...

【讨论】:

    猜你喜欢
    • 2013-08-04
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2011-07-02
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多