在perl中访问哈希变量的不同方法有哪些

时间:2016-02-26 12:12:47

标签: 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'};

它究竟意味着什么?有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:4)

您发布的所有三种变体在use strict下都会产生语法错误,而在Perl早于Perl 5.22的Perls上会发出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,并听取它向您显示的警告。

答案 1 :(得分:2)

这是早期perl版本的问题,其中包含类似

的表达式
%par->{'a'}

将被默默地解释为

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

我不清楚这是否是一个错误,或者它是否是预期的行为。无论哪种方式,它都被声明为不合需要,并且首先被记录为弃用,然后更改为导致弃用警告,最后在Perl v5.22中它会导致致命错误,因此您的代码甚至不会再编译

  

不能使用哈希作为参考

其中任何一个都应该正确地写成

$par{'a'}

perldelta document for version 22 of Perl 5有此

  

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

     

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

一般情况下,引用的三行应通过将%par->替换为$par来修复

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

然而,第二个将@a1设置为具有单个元素,并且最好可以写为@a1 = ( $par{'a'}{'c'} )以强调它是列表赋值,第三个是将单个标量分配给哈希,这将导致警告

  

哈希分配中奇数个元素

所以语义错误以及语法

相关问题