0

我正在三个文本文件中搜索四个特定基因名称之一(存储在 中$var#)。找到后,它会将在基因名称后找到的值添加到计数中。然后,我们通过总计$count_exp#并除以所有文件中的出现次数来平均该值。

当在每个文件中找不到基因名称时,让用户知道的正确方法是什么?我在处理这个循环/条件的流程时遇到了困难。

这是处理三个文本文件之一的代码片段......

    foreach $hyperosmotic(@hyperosmotic)
{
    @hyperosmotic1=split(/\t/,$hyperosmotic);
    $name=$hyperosmotic1[0];
    $exp=$hyperosmotic1[1];
    chomp $name;
    chomp $exp;
    if ($name eq $var1)
    {
    $count_exp1 = $count_exp1 + $exp;       
    $count_var1 = ++$count_var1;    
    }
    elsif ($name eq $var2)
    {
    $count_exp2 = $count_exp2 + $exp;
    $count_var2 = ++$count_var2;    
    }
    elsif ($name eq $var3)
    {
    $count_exp3 = $count_exp3 + $exp;
    $count_var3 = ++$count_var3;    
    }
    elsif ($name eq $var4)
    {
    $count_exp4 = $count_exp4 + $exp;
    $count_var4 = ++$count_var4;
    }
}
4

1 回答 1

3

你基本上想使用数组:

(和use strict; use warnings;

my @count_var = (0)x4;
my @count_exp = (0)x4;
my @var = ($var1, $var2, ...);

HYPEROSMOTIC:
for my $hyperosmotic (@hyperosmotic) {

    my ($name, $exp) = split /\t/, $hyperosmotic;

    for my $i (0 .. $#var) {
      if ($name eq $var[$i]) {
        $count_exp[$i] += $exp;
        $count_var[$i]++;
        next HYPEROSMOTIC; # jump into next iteration of the labeled loop
      }
    }

    # this code is only reached if no var matched:
    die qq[I don't have a var for name "$name"];
    # That just threw a fatal error. You may want to do something different.
}

您可以通过使用哈希来提高效率:

my %counts = (
  $var1 => {exp => 0, var => 0},
  $var2 => {exp => 0, var => 0},
  $var3 => {exp => 0, var => 0},
  $var4 => {exp => 0, var => 0},
);

for my $hyperosmotic (@hyperosmotic) {
  my ($name, $exp) = split ...;
  if (my $count = $counts{$name}) {
    $count->{exp} += $exp;
    $count->{var}++;
  } else {
    die qq[I don't have a var for name "$name"];
  }
}
于 2013-03-01T15:56:03.677 回答