http://www.perlmonks.org?node_id=468288

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

Fellow Monks!
I need your help and I beg for forgiveness if I am incorrectly using certain terminology (I ask for your merciful correction and enlightenment if needed in the matter).
In a nutshell I am looking to determine/conduct a listing of keys in this particular array of hashes:
$data[0]->{"level"}=12.8;
where "level" is one known key and there are other possible ones not known and I wish to list them.
How do I do this? I am betting that it is a simple one-liner.
Thank you. As always your help and wisdom are both greatly appreciated!!

Replies are listed 'Best First'.
Re: Listing Keys in a specific element(s) in an array of hashs
by robartes (Priest) on Jun 20, 2005 at 12:02 UTC
    print join ",",keys %{$data[0]};

    See perlfunc for docs on the use of keys.

    CU
    Robartes-

Re: Listing Keys in a specific element(s) in an array of hashs
by Fang (Pilgrim) on Jun 20, 2005 at 12:06 UTC

    I guess you want to traverse the array, and then traverse each hash elements. One solution could be:

    for my $hash (@data) { for (keys %$hash) { ... }

    If you simply want to list the keys of a hash, you can do:

    my @keys = keys %{$data[0]}; # or [1], or [2], ...

    Hope this helps.

      I guess you want to traverse the array, and then traverse each hash elements.

      Depending on what the data's being used for, for quickly printing any complex data structure you can often avoid writing any loops yourself just by using YAML (or Data::Dumper if you prefer):

      use YAML qw<Dump>; print Dump \@data;

      Smylers

Re: Listing Keys in a specific element(s) in an array of hashs
by davidrw (Prior) on Jun 20, 2005 at 12:15 UTC
    If you want all the unique keys from all the array elements, you can traverse it similar to as described above, and just keep track (in a hash) of the keys you've seen.
    my %allKeys; foreach my $i ( 0 .. $#data ){ my $hash = $data[$i]; for (keys %$hash) { push @{$allKeys{$_}}, $i; } } foreach my $key ( sort keys %allKeys ){ my $locations = $allKeys{$key}; printf "Key '%s' was seen %d times at these indices: %s\n", $key, scalar @$locations, join(", ", @$locations); }
Re: Listing Keys in a specific element(s) in an array of hashs
by anonymized user 468275 (Curate) on Jun 20, 2005 at 12:40 UTC
    My self-taught way was this, which means maybe others have better style...

    for ( my $i=0; $i<=$#data; $i++ ) { my $href = $data[$i]; for ( keys %$href ) { print "$_\n"; } }

    -S

      Most monks would suggest the more natural foreach for something like this, as it tends to cut down on "one-off" errors. Also, it tends to be more intuitive (at least after you've learned Perl; I can see how your way would be more intutitive to a person coming from C or Java).

      foreach my $href ( @data ) { for ( keys %$href ) { print "$_\n"; } }

          -Bryan