0

I am trying to access a specific variable member in the array in perl.

my $array = [];
@{$array} = (
             { 'family'  => "abc", 
               'roles'   => {},
             },
             { 'family'  => "def", 
               'roles'   => {
                              'member'=>["1234"],
                            },
             },
            );

I tried to access the values using

foreach (@{$array}){
   print " $_->{'family'} \n"; 
   #This is printing the family value 
}

Could someone explain to me how i could access the member field.i tried using $_->roles->{'member'} but this doesn't seem to work. any inputs here would be of great help.

I get the below output..i am not getting any error.

Hash(0x268d35)->roles->{'memeber'}

7
  • Do you get any errors? Commented Feb 5, 2019 at 20:09
  • $_->{'roles'}{'member'} among other ways. Commented Feb 5, 2019 at 20:29
  • Hi Shawn, i tried it but it doesnt work, i get ARRAY(0x28b38cc) Commented Feb 5, 2019 at 20:31
  • 1
    $_->{roles}->{member} is an array ref, so you'll need to de-reference it with @{ ... }. Otherwise it'll get again stringified, hence ARRAY(...). Commented Feb 5, 2019 at 20:48
  • May I point you to perlreftut? "If you try to use a reference like a string, you get strings like ARRAY(0x80f5dec) or HASH(0x826afc0)" Commented Feb 5, 2019 at 20:55

1 Answer 1

2

Try

# hash ref, key 'family' pointing to scalar
print $_->{family}, "\n";
# hash ref, key 'roles' pointing to hash ref,
#    key 'members' pointing to array ref 
print @{ $_->{roles}->{member} }, "\n";

Your hash reference got interpolated into a string, hence the HASH(...).

Complete code example based on your code:

#!/usr/bin/perl
use strict;
use warnings;

my $array = [
    {
        family => "abc",
        roles  => {},
    },
    {
        family => "def",
        roles  => {
            member => ["1234"],
        },
    },
];

for my $hash_ref (@{ $array }) {
    print "family ", $hash_ref->{family}, "\n";
    while (my($key, $value) = each %{ $hash_ref->{roles} }) {
        print "role '${key}' @{ $value }\n";
    }
}

exit 0;

Test run

$ perl dummy.pl
family abc
family def
role 'member' 1234
Sign up to request clarification or add additional context in comments.

3 Comments

:Thank you. i tried this, for this i get ARRAY(0xxxxxxxx).I am not getting the value in member field. Is there anything i am missing here.
See the updated full code example with test run. As you can see it works.
Thanks a lot Stefan, this works. Will read the perlreftut you sent.

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.