in reply to Hash key & foreach

Hi Anonymous,

Have a look at "hashes of hashes" in perldsc, for example:

use warnings; use strict; my @routers = ( "R1", "R2", "R3" ); my %if = ( R1 => { R1R0 => 1, R1R6 => 2, }, R2 => { R2R0 => 3, R2R6 => 1, }, R3 => { R3R61 => 2, R3R62 => 3, }, ); for my $r (@routers) { for my $i (keys %{ $if{$r} }) { print "Router $r Interface $i\n"; } } __END__ Router R1 Interface R1R0 Router R1 Interface R1R6 Router R2 Interface R2R0 Router R2 Interface R2R6 Router R3 Interface R3R61 Router R3 Interface R3R62

Alternatively, if you're stuck with the structure of the %interfaces hash, and the keys are always named beginning with the router's ID, you could use grep:

use warnings; use strict; my @routers = ( "R1", "R2", "R3" ); my %interfaces = ( R1R0 => 1, R1R6 => 2, R2R0 => 3, R2R6 => 1, R3R61 => 2, R3R62 => 3, ); for my $r (@routers) { my @ifs = grep {/^\Q$r\E\D/} keys %interfaces; for my $i (@ifs) { print "Router $r Interface $i\n"; } }

Hope this helps,
-- Hauke D

Replies are listed 'Best First'.
Re^2: Hash key & foreach
by Anonymous Monk on Jun 03, 2016 at 05:23 UTC

    Thanks. Let me try this and update