2014-10-01 134 views
0

之間的混亂,你會如何檢索$這個「A」在下面的代碼行:的Perl - 數組和散列

my $this = { 1 => "A", 2 => "B", 3 => "C" }; 

我新的Perl和有幾個問題,從上面的線。

1)首先,這是一個有效的代碼行嗎?

2)這是什麼樣的數據結構?我認爲它是散列,但下面的行並沒有給我'A'。

print "$this{1}"; 
+1

歡迎來到Perl。請注意,請務必包含['use strict;'](http://perldoc.perl.org/strict.html)和['use warnings;'](http://perldoc.perl.org/warnings。 html)在每個Perl腳本的頂部。在處理引用和複雜的數據結構時,它會幫助你很多。 – Miller 2014-10-03 23:36:57

回答

4

是的,那是一個匿名散列引用。

這大致相當於說:

my %hash = (1 => "A", 2 => "B", 3 => "C"); 

my $this = \%hash; 

要訪問值 「A」,你可以使用:

print $this->{1}; 

對於介紹到Perl中,我建議您閱讀Modern Perl Book。 Perl語言部分將討論數據結構和引用。

+0

在這種情況下,'$ this'將是一個*哈希引用*。然後' - >'在這裏進行解引用。 – 2014-10-01 02:39:35