2011-12-28 30 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