2011-12-28 32 views
0

我有一個數組在其中。它看起來像:訪問perl中的內部數組?

@test =(
    'mobilephone' => ['sony', 'htc'], 
    'pc' => ['dell', 'apple'] 
); 

如何打印出內部數組? 我有'手機',如果檢查變量是''手機',所以我想打印出索尼和HTC。怎麼樣?還是我有另一個錯誤?

+1

也許哈希是更好的呢? http://www.tizag.com/perlT/perlhashes.php – itdoesntwork 2011-12-28 15:38:44

+0

請不要鏈接到tiztag Perl教程。這是相當古老和討厭的代碼。相反,請嘗試http:// szabgab上的http://learn.perl.org或Gabor的快速增長教程。COM/perl_tutorial.html。 – 2011-12-29 08:42:45

回答

4

@test是錯誤的。你正在聲明一個散列。

始終在腳本的開頭使用use strict; use warnings;。你將能夠檢測到很多錯誤!

$test{key}會給你相應的數組引用:

#!/usr/bin/perl 

use strict; 
use warnings; 

my %test =(
    mobilephone => ['sony', 'htc'], 
    pc => ['dell', 'apple'] 
); 

my $array = $test{mobilephone}; 

for my $brand (@{$array}) { 
    print "$brand\n"; 
} 

# or 

for my $brand (@{ $test{mobilephone} }) { 
    print "$brand\n"; 
} 
+1

'warnings'不會捕獲這個錯誤。 OP對一個數組進行了完美的有效賦值。 – mob 2011-12-28 17:49:29

+1

@mob我知道,但他會在嘗試將它用作散列時發出警告。他只是發佈了這個定義,而不是嘗試使用它。 – Matteo 2011-12-28 19:40:23

1

通知我已經改變了你的測試到哈希

my %test =(
    'mobilephone' => ['sony', 'htc'], 
    'pc' => ['dell', 'apple'] 
); 

#Get the array reference corresponding to a hash key 
my $pcarray = $test{mobilephone}; 

#loop through all array elements 
foreach my $k (@$pcarray) 
{ 
    print $k , "\n"; 
} 

應該這樣做。

0

看起來更像是一個哈希賦值而不是數組賦值。

%test =(
    'mobilephone' => ['sony', 'htc'], 
    'pc' => ['dell', 'apple'] 
); 

在這種情況下,你想嘗試:

print Dumper($test{mobilephone}); 
1

這不是一個數組,它是一個哈希:

%test =(
    'mobilephone' => ['sony', 'htc'], 
    'pc' => ['dell', 'apple'] 
); 

my $inner = $test{'mobilephone'}; # get reference to array 
print @$inner;     # print dereferenced array ref 

或者

print @{$test{'mobilephone'}}; # dereference array ref and print right away 
3

你可能需要一個散列(由%印記,這是Perl的一個關聯數組名稱(用字符串作爲鍵)的集合指定)。如果是這樣,其他4個答案之一將幫助你。如果你真的想出於某種原因數組(如果您的數據可以有多個名稱相同的密鑰,或者如果你需要保存的數據的順序),你可以使用下面的方法之一:

my @test = (
    mobilephone => [qw(sony htc)], 
    pc'   => [qw(dell apple)] 
); 

與for循環:

for (0 .. $#test/2) { 
    if ($test[$_*2] eq 'mobilephone') { 
     print "$test[$_*2]: @{$test[$_*2+1]}\n" 
    } 
} 

使用一個模塊:

use List::Gen 'every'; 
for (every 2 => @test) { 
    if ($$_[0] eq 'mobilephone') { 
     print "$$_[0]: @{$$_[1]}\n" 
    } 
} 

另一種方式:

use List::Gen 'mapn'; 
mapn { 
    print "$_: @{$_[1]}\n" if $_ eq 'mobilephone' 
} 2 => @test; 

與方法:

use List::Gen 'by'; 
(by 2 => @test) 
    ->grep(sub {$$_[0] eq 'mobilephone'}) 
    ->map(sub {"$$_[0]: @{$$_[1]}"}) 
    ->say; 

每個版畫mobilephone: sony htc

免責聲明:我寫List::Gen