使用匹配和不匹配条件识别散列中的项目

Identify items in hash with matching and non-matching criteria

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

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

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
}

对于代码片段,我深表歉意;我试图保留相关信息。由于文件的大小,我不能逐行强制执行它。

否定运算符 ! 在其参数上强制执行布尔上下文。 "+""-" 在布尔上下文中都为真,因此 ! $strand 始终为假,即 "" 在字符串上下文中。

在散列中存储布尔值

$strand = $strand eq '+';

或者不使用布尔取反:

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

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

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

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