in reply to How do I access values in a hash by two different keys?

If you keep filename as your key, you could write your loop as

for my $i ( keys %{ $config->{item} } ) { print $config->{item}->{$i}->{id}, ": "; print $config->{item}->{$i}->{destination_dir}, "\n"; }

If you need it sorted by id, it goes like this:

for my $i (sort { $config->{item}->{$a}->{id} <=> $config->{item}->{$b +}->{id} } keys %{ $config->{item} } ) { print $config->{item}->{$i}->{id}, ": "; print $config->{item}->{$i}->{destination_dir}, "\n"; }

Replies are listed 'Best First'.
Re^2: How do I access values in a hash by two different keys?
by turbodizik (Initiate) on Jul 19, 2013 at 09:12 UTC
    It is a very good solution, thank you!
    But I have a question: Why this code works
    for my $i ( keys %{ $config->{item} } ) { print $config->{item}->{$i}->{destination_dir}; }
    and this one not?
    for (my $i=0; $i < 4; $i++ ) { print $config->{item}->{$i}->{destination_dir}; }
    I mean, it is nearly the same... I just say how often the loop should go and then I access via the index {$i}. Or not?
    Even print $config->{item}->{1}->{destination_dir}; this one doesn't work...
    I just want to understand. Thank you again!

      Have a look at your data structure using Data::Dumper:

      use Data::Dumper; print Dumper $config; gives you $VAR1 = { 'item' => { 'AMEX' => { 'destination_dir' => 'test', 'id' => 0 }, 'bla' => { 'destination_dir' => 'test1', 'id' => 1 }, 'alb' => { 'destination_dir' => 'test2', 'id' => 2 } } };

      So $config->{item} represents a reference to a hash with keys "AMEX", "bla", and "alb". If you try $config->{item}->{1}->{destination_dir}; you are using a key that does not exist, the string "1".

      UPDATE: I probably should state explicitely that there is no numeric index in a hash and that there is no defined order of items in a hash that you can rely on.

        Now I understand! :) Thank you very much!