3

I am trying to access elements of an array which is part of a hash.

for my $idx ( 0 .. $#vss ) {
    push (@{$vsnhash->{$vss[$idx]}}, $vsports[$idx]);
}
print Dumper(\%$vsnhash);

($VAR1 = {
      'name2' => [
                   '8001',
                   '8002'
                 ],
      'name1' => [
                   '8000'
                 ]
    };

I an able to access the keys with a foreach loop:

foreach my $key ( keys %$vsnhash ) {
print "$key\n";
}

How do I access the array of port numbers ('8001' , '8002') within the hash?
Thank you for the help!

0

3 Answers 3

5
while (my ($k, $v) = each %$vsnhash) {
    print "$k: @$v\n";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wow. I have no idea how this works but it's cool to learn new stuff :)
@FailedDev: It's fairly simple actually. each is like keys but gives you key and value at the same time. @$v is short for @{$v} and dereferences an array reference.
1
foreach my $key ( keys %$vsnhash ) {
   print "$key\n";
   foreach my $port (@{$vsnhash->{key}}){
      print "Port $port\n";
   }
}

1 Comment

Basically correct, but you've got some syntax errors. Should be: foreach my $port (@{$vsnhash->{$key}}){ instead of foreach my $port (@{$vsnhash{key}}){
1
$vsnhash{name2}->[0];   #8001
$vsnhash{name2}->[1];   #8002
$vsnhash{name1}->[0];   #8000

Code wise:

foreach my $key (sort keys %vsnhash) {
   foreach my $index (0..$#{$key}) {
      print "\$vsnhash{$key}->[$index] = " . $vsnhash{$key}->[$index] . "\n";
   }
}

The $#{$key} means the last entry in the array @{$key}. Remember that $key is a reference to an array while @{$key} is the array itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.