2016-02-26 69 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'})被固定強調這是一個列表分配,第三個是將單個標量分配給散列,這將導致警告

奇數在散列分配

元件所以語義是錯誤的,以及語法