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

my %interfaces = ( R1R0 => 1, R1R6 => 2, R2R0 => 3, R2R6 => 1, R3R61 => 2, R3R62 => 3, ); push (@routers, $r[1],$r[2],$r[3]); foreach my $rh (@routers) { $rh->config(" deactivate $interfaces{$R1R0}"); }

In the above code, there are 6 interfaces, 2 from each router, (R1, R2, R3). I want to deactivate each interface as defined in hash from all the routers. For that, am doing a foreach (to get the router handles separately), and execute the action. The problem with this is, when foreach executes the first router, say $r[0], only the first interface (defined in hash/key as R1R0) is executed. I want to execute both (first and second hash/key pair for R1), when foreach is executed for $r[0], similarly for R2 and R3. I found the only way is defined a seperate hash for all the three routers as below

%interfaces_R1 = ( R1R0 => R1R6 => ); %interfaces_R2 =( ...

Is there a better way to do it

Replies are listed 'Best First'.
Re: Hash key & foreach
by haukex (Archbishop) on Jun 02, 2016 at 13:12 UTC

    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

      Thanks. Let me try this and update