在perl中访问内部数组?

在perl中访问内部数组?,perl,multidimensional-array,Perl,Multidimensional Array,我有一个数组,里面有一个数组。它看起来像: @test =( 'mobilephone' => ['sony', 'htc'], 'pc' => ['dell', 'apple'] ); 如何打印出内部数组? 我有‘mobilephone’,如果check变量是==‘mobilephone’,那么我想打印出索尼和htc。怎样还是我犯了另一个错误?注意,我已将您的测试更改为哈希 应该这样做。这看起来更像是散列赋值,而不是数组赋值 %test =( 'mobilepho

我有一个数组,里面有一个数组。它看起来像:

@test =(
  'mobilephone' => ['sony', 'htc'],
  'pc' => ['dell', 'apple']
);
如何打印出内部数组?
我有‘mobilephone’,如果check变量是==‘mobilephone’,那么我想打印出索尼和htc。怎样还是我犯了另一个错误?

注意,我已将您的测试更改为哈希


应该这样做。

这看起来更像是散列赋值,而不是数组赋值

%test =(
    'mobilephone' => ['sony', 'htc'],
    'pc' => ['dell', 'apple']
);
在这种情况下,您可以尝试:

print Dumper( $test{mobilephone} );

这不是数组,而是散列:

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

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

@测试是错误的。您正在声明散列

始终严格使用;使用警告;在脚本的开头。您将能够检测到许多错误

$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";
}

您可能需要一个由%sigil指定的散列,它是一个关联数组的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


免责声明:我写道。

也许散列更适合这个?请不要链接到tiztag Perl教程。这是一个相当古老和肮脏的代码。相反,请尝试或使用Gabor在上快速增长的教程。warnings不会捕获此错误。OP对数组进行了完全有效的赋值。@mob我知道,但他在尝试将其用作哈希时会收到警告。他只是发布了定义,而不是试图使用它。
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;