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


In reply to Re: Hash key & foreach by haukex
in thread Hash key & foreach by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.