user2742160
user2742160

Reputation: 11

Extracting specific elements from hash

my %hash = {
    'student1' => {
        'Name' => 'aaa',
        'Age'  => '20',
        'Subjects' => ['Maths','Science']
    },
    'student2' => {
        'Name' => 'bbb',
        'Age'  => '22',
        'Subjects' => ['English','Science']
    }
}
my $hashRef = \%hash;

how do i extract the second subject name from this using hashref ?

Upvotes: 1

Views: 73

Answers (3)

DavidEG
DavidEG

Reputation: 5957

Your code is wrong, { } creates a hashref and you are storing it in a hash. You should do:

my %hash = (
    'student1' => {
        'Name' => 'aaa',
        'Age'  => '20',
        'Subjects' => ['Maths','Science']
    },
    'student2' => {
        'Name' => 'bbb',
        'Age'  => '22',
        'Subjects' => ['English','Science']
    }
);

my $hashRef = \%hash;

or even better:

my $hashref = {
    student1 => { ... },
    student2 => { ... },
};

Then you can access with:

$hashRef->{student2}->{Subjects}[1]

Upvotes: 2

Toto
Toto

Reputation: 91518

Your declaration of %hash is incorrect, do this instead:

my %hash = (
    'student1' => {
        'Name' => 'aaa',
        'Age'  => '20',
        'Subjects' => ['Maths','Science']
    },
    'student2' => {
        'Name' => 'bbb',
        'Age'  => '22',
        'Subjects' => ['English','Science']
    }
);

Note the parens instead og brace.

Then to get the second subject :

say $hashRef->{student1}{Subjects}[1];

Upvotes: 2

choroba
choroba

Reputation: 242343

Subjects are an array reference inside a hash inside a hash.

$hashRef->{student1}{Subjects}[1]

Also, do not use curly brackets to initilize a hash, they create an anonymous hash. Use round parentheses:

my %hash = ( ... );

Upvotes: 0

Related Questions