Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi there Monks!
I have this data structure and I need to print only the first name out of it by accessing it directly:
… print Dumper @data; …. $VAR1 = { 'firstname' => 'Mary', 'lastname' => 'Lou', 'id' => '5252', 'email' => 'test@test.com', 'date' => '03/03/2014', 'olddate' => '03-23-2013', 'page' => 'no page', }; ... print "$$data{'firstname'}\n";
Thanks!

Replies are listed 'Best First'.
Re: Get one element from anonymous hash
by Cristoforo (Curate) on Mar 23, 2014 at 22:41 UTC
    print "$$data{'firstname'}\n";

    Likely you want print "$data[0]{'firstname'}\n"; or what ever array index you need.

    for my $i (0 .. $#data) { print $data[$i]{firstname}, "\n"; }
      Yes, that's right, thank you!
      What if I need to add an element to it?
        You have an "Array of hash-refs" - usually referred to as AOH.

        Adding data is like adding to the end of an array:

        push @data, { 'firstname' => 'Suzy', 'lastname' => 'Wong', 'id' => '5253', 'email' => 'test2@test.com', 'date' => '04/03/2014', 'olddate' => '04-23-2013', 'page' => 'no page', };

                What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?
                      -Larry Wall, 1992

        for my $i (0 .. $#data) { $data[$i]{'stuff'} = 'more stuff'; }
Re: Get one element from anonymous hash
by Laurent_R (Canon) on Mar 24, 2014 at 07:52 UTC
    Your data structure would probably be clearer to you if you used Dumper on a reference to the data:
    print Dumper \@data;