使用匹配和不匹配条件识别哈希中的项目

时间:2018-08-30 13:01:36

标签: arrays perl hash matching

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

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

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不匹配的元素(其二进制值均为两个符号)。

我将以下内容放到上一个while之后的同一for块中,但似乎不起作用

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
}

我为代码片段道歉;我试图保留相关信息。由于文件的大小,我无法逐行逐行进行暴力破解。

1 个答案:

答案 0 :(得分:1)

否定运算符!对其参数执行布尔上下文。 "+""-"在布尔上下文中均为true,因此! $strand始终为false,即在字符串上下文中为""

将布尔值存储在哈希中

$strand = $strand eq '+';

或者不要使用布尔求反:

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

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

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

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