Your code has a bug. In the regex in "if ($line =~ m/^interface (\.*)/) {" you have escaped the dot, which isn't what you want. The regex should be "/^interface (.*)/)".

Less importantly, you are using a leading ampersand in the sub calls "&parse_ethernet($1);" and "&parse_gigabit($1);". They are unnecessary and you shouldn't use them unless you know what they do and want tthe effect. Here, you don't.

As for your parsing problem, you can set the input separator to "!\n" when you read the file. Then you will have one complete chunk of input to give to any of the subs parse_* or whatever. Note that these must now expect a multiline string containing all the information in the current chunk.

Here is a sketch:

$/ = "!\n"; while ( <DATA> ) { chomp; if ( /^interface (.*)/ ) { if ( $1 eq 'Ethernet' ) { parse_ethernet( $_); } elsif ( $1 eq 'Gigabit' ) { parse_gigabit( $_); } } elsif ( /^system (.*)/ ) { # blah... } } sub parse_gigabit { my $chunk = shift; $chunk =~ tr/\n/ /; print "GIGABIT: $chunk\n"; } sub parse_ethernet { my $chunk = shift; $chunk =~ tr/\n/ /; print "ETHERNET: $chunk\n"; } __DATA__ ! interface Ethernet blah... blah... ! interface Gigabit blah... blah... ! interface Ethernet blah... !
Anno

In reply to Re: Need advice on how to break foreach parsing loop into functions by Anno
in thread Need advice on how to break foreach parsing loop into functions by ewhitt

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.