【问题标题】:Identify items in hash with matching and non-matching criteria使用匹配和不匹配条件识别哈希中的项目
【发布时间】:2019-02-05 10:38:16
【问题描述】:

我有两个制表符分隔的文件: 一个是包含数千个条目的参考 另一个是数百万个标准的列表 用于搜索参考。

我使用以下代码对参考文件进行哈希处理

use strict;
use warnings;

#use Data::Dumper;
#use Timer::Runtime;

use feature qw( say );

my $in_qfn          = $ARGV[0];
my $out_qfn         = $ARGV[1];
my $transcripts_qfn = "file";

my %transcripts;

{
   open(my $transcripts_fh, "<", $transcripts_qfn)
      or die("Can't open \"$transcripts_qfn\": $!\n");

   while ( <$transcripts_fh> ) {
      chomp;
      my @refs = split(/\t/, $_);
      my ($ref_chr, $ref_strand) = @refs[0, 6];
      my $values =  {
         start => $refs[3],
         end   => $refs[4],
         info  => $refs[8]
      };

      #print Data::Dumper->Dump([$values]), $/; #confirm structure is fine
      push @{ $transcripts{$ref_chr}{$ref_strand} }, $values;
   }  
}

然后我打开另一个输入文件,定义元素,并解析哈希以找到匹配条件

while ( <$in_fh> ) {
  chomp;
  my ($x, $strand, $chr, $y, $z) = split(/\t/, $_);

  #match the reference hash for things equal to $chr and $strand
  my $transcripts_array = $transcripts{$chr}{$strand};

  for my $transcript ( @$transcripts_array ) {
     my $start = $transcript->{start};
     my $end   = $transcript->{end};
     my $info  = $transcript->{info};

     #print $info and other criteria from if statements to outfile, this code works
  }
}

这可行,但我想知道我是否可以在哈希中找到匹配 $chr 但不匹配 $strand(具有任一符号的二进制值)的元素。

我在前一个 for 之后将以下内容放入同一个 while 块中,但它似乎不起作用

my $transcripts_opposite_strand = $transcripts{$chr}{!$strand};

for my $transcript (@$transcripts_opposite_strand) {

   my $start = $transcript->{start};
   my $end   = $transcript->{end};
   my $info  = $transcript->{info};

   #print $info and other criteria from if statements
}

我为代码 sn-ps 道歉;我试图保留相关信息。由于文件的大小,我不能真正通过逐行进行暴力破解。

【问题讨论】:

    标签: arrays perl hash matching


    【解决方案1】:

    否定运算符! 对其参数强制执行布尔上下文。 "+""-" 在布尔上下文中都是 true,所以 ! $strand 总是 false,即 "" 在字符串上下文中。

    在哈希中存储布尔值

    $strand = $strand eq '+';
    

    或者不使用布尔否定:

    my $transcripts_opposite_strand = $transripts{$chr}{ $strand eq '+' ? '-' : '+' };
    

    三元运算符可以替换为更短但可读性较差的替代方案,例如

       qw( + - )[ $strand eq '+' ]
    

    因为在数字上下文中,true 被解释为 1,false 被解释为 0。

    【讨论】:

    • 我使用了忽略布尔否定的第二个建议并且脚本有效。干杯。
    猜你喜欢
    • 2021-04-23
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2019-10-10
    • 1970-01-01
    相关资源
    最近更新 更多