Use a hash of arrays
my %matches; my $section; ... if ( $line =~ m/^(Router|Network|Extern)/ ) { $section = $1; } push @{ $matches{$section} }, $line;

And I'd stay clear of Switch if I were you. It can lead to some difficult to trace bugs.

update

Here's a reimplementation of your subroutine, along with example usage

use Data::Dumper; my $matches = ospf2_split_database( "no match\n", "Extern 1\n", "Network 1\n", "Stuff for Network 1a\n", "Stuff for Network 1b\n", "Stuff for Network 1c\n", "Network 2\n", "Stuff for Network 2a\n", "Stuff for Network 2b\n", "Router 1\n", "Router 2\n", "Extern 2\n", ); print Dumper $matches->{Network}; sub ospf2_split_database { my %matches; my @ospf2database = @_; my $section; for my $line ( @ospf2database ) { chomp $line; if ( $line =~ m/^(Router|Network|Extern)/ ) { $section = $1 } push @{ $matches{$section} }, $line if $section; } return \%matches; }

Update^2: Now meets the clarified spec


In reply to Re: Is there a better way to approach this? by FunkyMonk
in thread Is there a better way to approach this? 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.