Perl 错误:在 Test.pl 行 "n"、<File> 行 2 处使用 "strict refs" 时无法使用字符串 (" ") 作为 HASH 引用

Perl errors: Can't use string (" ") as a HASH ref while "strict refs" in use at Test.pl line "n", <File> line 2

我目前正在编写一个将文件作为输入的脚本。输入文件如下所示:

ECHANTILLON GENOTYPE    
CAN1        genotype1   
CAN2        genotype1   
CAN3        genotype1   
EUG1        genotype2   
EUG2        genotype2   
EUG3        genotype2   
EUG4        genotype2

我想做的是创建一个散列:

我的脚本如下所示:

#!/usr/local/perl-5.24.0/bin/perl
use warnings;
use strict;

use Data::Dumper;
use feature qw{ say };
use Getopt::Long; 



my $list_geno;

GetOptions("g|input=s"=>$list_geno);
my %hash_geno_group;

open(GENOTYPED,"<$list_geno") or die ("Cannot open $list_geno\n");
while (defined(my $l1= <GENOTYPED>)) 
    {
        my @geno_group_infos = split(m/\t/,$l1); 
        next if ($l1 =~ m/^ECHANTILLON/); 
        chomp($l1);
        my $sample_nm = $geno_group_infos[0]; 
        my $sample_geno_group = $geno_group_infos[1]; 
        push @{ $hash_geno_group{$sample_geno_group}{"sample"} },$sample_nm;
        foreach $sample_geno_group (keys (%hash_geno_group)){
            foreach $sample_nm (values %{$hash_geno_group{%{$sample_geno_group}{"sample"}}}){
            print $sample_geno_group, "\t" ,  $sample_nm, "\n";
}
}
}


close(GENOTYPED);
exit;

我试图检查 returns $sample_nm 变量的打印内容,但它 returns 我认为是错误

Can't use string ("genotype1") as a HASH ref while "strict refs" in use at Test.pl line 27, "GENOTYPED" line 2". 

谁能解释一下:

替换行

foreach $sample_nm (values %{$hash_geno_group{%{$sample_geno_group}{"sample"}}}){

foreach $sample_nm (@{$hash_geno_group{$sample_geno_group}{"sample"}}){

$sample_geno_group 是散列 %hash_geno_group 的键,即。一个字符串(在您的示例中为 genotype1genotype2)。但是,当您执行 %{$sample_geno_group} 时,您将其取消引用,就好像它是哈希引用一样,因此会出现错误 Can't use string as HASH ref ...

此外,values %{ xxx } 应该用于检索 xxx 引用的散列值。但在您的情况下,xxx(即 $hash_geno_group{$sample_geno_group}{"sample"})是对数组的引用,您在其中插入了上面两行带有 push ... 的元素。所以 @{ xxx } 应该用来检索它的元素(就像我在我建议的修复中所做的那样)。


另一个建议:使用用 my 声明的变量而不是你的裸词 GENOTYPED(例如,open my $genotype, '<', $list_geno or die "Can't open '<$list_geno': $!")。