Reputation: 333
I have an array with an array in it. It looks like:
@test =(
'mobilephone' => ['sony', 'htc'],
'pc' => ['dell', 'apple']
);
How can I print out the inner array? I have 'mobilephone' and if the check variable is == 'mobilephone', so I want to print out sony and htc. How? Or is there another mistake by me?
Upvotes: 0
Views: 113
Reputation: 40152
You probably want a hash (designated by the %
sigil, which is Perl's name for an associative array (a collection with strings as keys)). If so, one of the other 4 answers will help you. If you actually wanted an array for some reason (if your data can have multiple keys with the same name, or if you need to preserve the order of the data), you could use one of the following methods:
my @test = (
mobilephone => [qw(sony htc)],
pc' => [qw(dell apple)]
);
with a for loop:
for (0 .. $#test/2) {
if ($test[$_*2] eq 'mobilephone') {
print "$test[$_*2]: @{$test[$_*2+1]}\n"
}
}
using a module:
use List::Gen 'every';
for (every 2 => @test) {
if ($$_[0] eq 'mobilephone') {
print "$$_[0]: @{$$_[1]}\n"
}
}
another way:
use List::Gen 'mapn';
mapn {
print "$_: @{$_[1]}\n" if $_ eq 'mobilephone'
} 2 => @test;
with methods:
use List::Gen 'by';
(by 2 => @test)
->grep(sub {$$_[0] eq 'mobilephone'})
->map(sub {"$$_[0]: @{$$_[1]}"})
->say;
Each block prints mobilephone: sony htc
Disclaimer: I wrote List::Gen.
Upvotes: 3
Reputation: 14940
@test
is wrong. You are declaring a hash.
Always use use strict; use warnings;
at the beginning of your script. You will be able to detect many errors!
$test{key}
will give you the corresponding array reference:
#!/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";
}
Upvotes: 4
Reputation: 67910
That's not an array, it's a hash:
%test =(
'mobilephone' => ['sony', 'htc'],
'pc' => ['dell', 'apple']
);
my $inner = $test{'mobilephone'}; # get reference to array
print @$inner; # print dereferenced array ref
Or
print @{$test{'mobilephone'}}; # dereference array ref and print right away
Upvotes: 1
Reputation: 23085
That looks more like a hash assignment than an array assignment.
%test =(
'mobilephone' => ['sony', 'htc'],
'pc' => ['dell', 'apple']
);
In this case, you'd try:
print Dumper( $test{mobilephone} );
Upvotes: 0
Reputation: 24413
Notice I have changed your test to a hash
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";
}
should do it.
Upvotes: 1