$Interaction{$TrGene}={ CisGene => $CisGene,E => $e,Q => $q,};
单个$TrGene与许多CisGenes(具有唯一的E& Q)相关联.
例如:
TrGene1 CisGene1 Q1 E2
TrGene1 CisGene2 Q2 E3
最后一个TrGene1覆盖了它之前的那些.我认为我需要创建一个数组的引用,但是在阅读这个网页之后不完全理解应该怎么做:http://perldoc.perl.org/perlreftut.html
我试图在该网页上使用国家/城市示例,但效果不是很好:
$Interaction{$TrGene}={ CisGene => $CisGene,}; push @{$Interaction{$TrGene}},$CisGene;
我收到错误’Not a ARRAY ref’.我也只在那里使用了$CisGene,但它不需要覆盖E&该CisGene的Q值. (这个哈希知道CisGene是否与特定的E和Q相关联,或者我是否需要为此创建另一层哈希?)
谢谢
解决方法
$Interaction{$TrGene} = { CisGene => $CisGene,E => $e,Q => $q,$CisGene;
代码解释:
您使用大括号{}将键值对列表分配给匿名哈希,并将该哈希引用分配给%Interaction哈希中的$TrGene键.然后,您尝试使用@ {…}将其作为数组引用,但这不起作用.
如果输入具有不同值的哈希键,则会覆盖它们.我们来看一些实际的例子,这真的很容易.
$Interaction{'foobar'} = { CisGene => 'Secret code',E => 'xxx',Q => 'yyy',};
现在,您已在密钥“foobar”下存储了哈希引用.该哈希实际上是对数据结构的独立引用.如果您将它们视为标量,我认为跟踪结构会更容易:哈希(或数组)只能包含标量.
hash%Interaction可能包含许多键,如果您输入了上述数据,则所有值都将是哈希引用.例如.:
$hash1 = { # note: curly brackets denote an anonymous hash CisGene => 'Secret code',}; $hash2 = { CisGene => 'some other value',E => 'foo',Q => 'bar',}; %Interaction = ( # note: regular parenthesis denote a list 'foobar' => $hash1,# e.g. CisGene => 'Secret code',... etc. from above 'barbar' => $hash2 # e.g. other key value pairs surrounded by {} ... );
$hash1和$hash2中包含的值类型现在是引用,是内存中数据的地址.如果你打印出来打印$hash1,你会看到类似HASH(0x398a64)的东西.
现在,如果使用现有密钥在%Interaction中输入新值,则该密钥将被覆盖.因为哈希键只能包含一个值:标量.在我们的例子中,对哈希的引用.
你在你的例子中尝试做的是使用’foobar’键的值作为数组引用(这是愚蠢的,因为你现在可以看到,它是一个哈希引用):
push @{$Interaction{$TrGene}},$CisGene;
改写:
push @{ $hash1 },'Secret code'; # using the sample values from above
不……那不行.
你需要的是一个新的容器.我们将键’foobar’的值改为数组引用:
%Interaction = ( 'foobar' => $array1,... );
哪里:
$array1 = [ $hash1,$hash2 ];
要么
$array1 = [ # note the square brackets to create anonymous array { # curly brackets for anonymous hash CisGene => 'Secret code',},# comma sign to separate array elements { # start a new hash CisGene => 'Some other value',} # end ]; # end of $array1
现在,这完全是一种放置东西的麻烦方式,所以让我们简单一点:
$CisGene = 'foobar'; $e = 'xxx'; $q = 'yyy'; my $hash1 = { CisGene => $CisGene,}; push @{$Interaction{$TrGene}},$hash1;
或者你可以取消临时变量$hash1并直接分配它:
push @{$Interaction{$TrGene}},{ CisGene => $CisGene,};
并且在访问元素时:
for my $key (keys %Interaction) { # lists the $TrGene keys my $aref = $Interaction{$key}; # the array reference for my $hashref (@$aref) { # extract hash references,e.g. $hash1 my $CisGene = $hashref->{'CisGene'}; my $e = $hashref->{'E'}; my $q = $hashref->{'Q'}; } }
注意直接处理引用时使用箭头运算符.你也可以说$$hashref {‘CisGene’}.
或直接:
my $CisGene = $Interaction{'foobar'}[0]{'CisGene'};
我建议阅读perldata.一个非常方便的模块是Data::Dumper.如果你这样做:
use Data::Dumper; print Dumper \%Interaction; # note the backslash,Dumper wants references
它会为您打印出您的数据结构,这使您可以很容易地看到自己在做什么.记下使用括号和大括号来表示数组和散列.