2016-02-26 70 views
4

根据我的基本理解如下,我们可以访问散列值的不同方法:什么是访问的散列变量在Perl

$hash_name{key1}{key2};  #In case of an nested hash 
$hash_reference->{key1}{key2} #if we have the reference to the hash instead of the hash we can access as 

如下但是在一个存档的代码中,我所看到的:

$sc1 = %par->{'a'}{'b'}; 
@a1 = %par->{'a'}{'c'}; 
%c3 = %par->{'a'}{'d'}; 

这实际上是什么意思?有人能帮助我吗?

+6

它意味着一个错误。把它扔掉。 –

回答

4

您发布的所有三种变体都会在use strict之下产生语法错误,并且在Perls 5.22之前的Perl上会出现use warnings的额外警告。我在这里展示的输出来自Perl 5.20.1。

use strict; 
use warnings; 

my $par = { a => { b => 1, c => 2, d => 3 } }; 

my $sc1 = %par->{'a'}{'b'}; 
my @a1 = %par->{'a'}{'c'}; 
my %c3 = %par->{'a'}{'d'}; 

__END__ 
Using a hash as a reference is deprecated at /home/foo/code/scratch.pl line 700. 
Using a hash as a reference is deprecated at /home/foo/code/scratch.pl line 701. 
Using a hash as a reference is deprecated at /home/foo/code/scratch.pl line 702. 
Global symbol "%par" requires explicit package name at /home/foo/code/scratch.pl line 700. 
Global symbol "%par" requires explicit package name at /home/foo/code/scratch.pl line 701. 
Global symbol "%par" requires explicit package name at /home/foo/code/scratch.pl line 702. 
Execution of /home/foo/code/scratch.pl aborted due to compilation errors. 

没有strictwarnings,它会编译,但产生的废话。

no strict; 
no warnings; 
use Data::Printer; 

my $par = { a => { b => 1, c => 2, d => 3 } }; 

my $sc1 = %par->{'a'}{'b'}; 
my @a1 = %par->{'a'}{'c'}; 
my %c3 = %par->{'a'}{'d'}; 

p $sc1; 
p @a1; 
p %c3; 

__END__ 

undef 
[ 
    [0] undef 
] 
{ 
    '' undef 
} 

这就是说,永远为你的Perl程序use strictuse warnings,听它表明你的警告。

+0

表达式'%par - > {'a'} {'b'}'在5.22之前的所有版本的Perl中被编译为'\(%par) - > {'a'} {'b'}'哈希引用'$ par'的存在是无关紧要的。如果你声明'my%par =(a => {b => 1,c => 2,d => 3})'并在Perl v5.20或更早的版本上测试过,那么'Data :: Dump'至少会显示一些有用的东西,尽管语法肯定是错误的,并已被弃用很长时间 – Borodin

+0

@Borodin我明白了。我会将我的Perl版本添加到答案中。 – simbabque

+0

@Borodin所以我在上面的问题中发布的代码($ sc1 =%par - > {'a'} {'b'};)“有什么意义? –

2

这起源与早期的perl版本的问题,即像一个表达

%par->{'a'} 

会默默地解释为

(\%par)->{'a'} 

我不清楚这是否是一个错误,或者如果它是有意的行为。无论哪种方式,它被宣布是不受欢迎的,并且首先被记录为不推荐使用,然后更改为引起弃用警告,并且最终在Perl v5.22中它会导致致命错误,因此您的代码将不再编译任何更长的代码

不能使用哈希作为参考

这些要么应该适当地写成只是

$par{'a'} 

perldelta document for version 22 of Perl 5有这个

使用散列或数组作为参考现在是致命错误

例如,现在%foo->{"bar"}导致致命编译错误。自v5.8之前,这些已被弃用,并从那时起提出弃用警告。

一般来说,你引用的三条线应该由$par

$sc1 = $par{'a'}{'b'}; 
@a1 = $par{'a'}{'c'}; 
%c3 = $par{'a'}{'d'}; 

更换%par->但是第二个会设置@a1有一个单一的元素,也许可以更好地被写为@a1 = ($par{'a'}{'c'})被固定强调这是一个列表分配,第三个是将单个标量分配给散列,这将导致警告

奇数在散列分配

元件所以语义是错误的,以及语法