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

hi brothers, This might sound stupid but, how do I get the key name of my array using a loop? let's say theres :
my @item; my $val; $item["A"] = (["dunno", "i think so"]); $item["B"] = (["okay", "duh"]); foreach $val(@item){ #$val holds array A and B's 0 position, but no other parameters to get its key name instead. }
unlike php, where i could actually do this :
foreach($item as $key=>$value) { //where $key is keyname, and $value is the value }
anyway to do this..without asking me to change it to hashes?

Replies are listed 'Best First'.
Re: how to get array's key name?
by Corion (Patriarch) on Feb 22, 2008 at 08:55 UTC

    Perl arrays cannot be indexed by strings. If you had #!/usr/bin/perl -w or use warnings;, Perl would have told you so. If you need strings as keys, you need a hash. But you need to know that hash keys are unordered. If you need a hash where the hash keys are in an order specified by you, either use a parallel hash and an array for the keys, or use Tie::IxHash.

    If you just want to iterate over the keys and values of a hash, just use the each keyword, but you need to store your data in a hash, still.

    my %item; $item{"A"} = ["dunno", "i think so"]; $item{"B"} = ["okay", "duh"]; foreach $val (keys %item) { print "$val => @{ $item{$val}}\n"; }
Re: how to get array's key name?
by wfsp (Abbot) on Feb 22, 2008 at 11:31 UTC
    Generally, a good rule of thumb is
    • if order is important use an array
    • if a 'lookup' is important use a hash
    It is possible to combine the two with an array of hashes (AoH). And you can use perl's each to get at the key/value pairs in the hashes.
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; $Data::Dumper::Indent = 1; $Data::Dumper::Sortkeys = 1; my @db = ( {one => q{red}}, {two => q{green}}, {three => q{blue}}, ); #print Dumper \@db; for my $rec (@db){ my ($key, $value); while (($key, $value) = each %{$rec}){ print qq{$key -> $value\n}; } }
    produces:
    one -> red two -> green three -> blue
Re: how to get array's key name?
by adrive (Scribe) on Feb 22, 2008 at 09:07 UTC
    thanks, im just too used to using associative arrays. I'll change it to hashes tehn.
      "associative arrays" is another name for "hash", but awfully long to write :o)