in reply to Is there a better way to approach this?

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

Replies are listed 'Best First'.
Re^2: Is there a better way to approach this?
by ewhitt (Scribe) on Mar 29, 2008 at 09:51 UTC
    Thanks for the response. I forgot to mention one thing - not all the lines have what I am matching for. So once I match, I need the following lines to dump into a specific array until another match occurs, when switching to the appropriate array. Thanks!

      FunkyMonk's solution is still the right thing to do for the data structure. The only thing this new requirement adds is that you need to save every line you see somewhere; the last match determines the "where".

      Sample script:

      #!/usr/bin/perl -w use strict; my ($state, %data); for (<DATA>){ $state = $1 if /^(Router|Network|Extern)/; push @{$data{$state}}, $_; } # Display the saved data for my $st (sort keys %data){ print "$st:\n"; for (@{$data{$st}}){ print "\t$_"; } } __DATA__ Router abc def ghi jkl Network Extern foo bar qux zotz Router blah Network

      Update: I had originally thought to number the lines, so I had the innermost loop in the 'display' section traverse the indexes. Since I'm just displaying the lines, I've gone back to walking the list itself - so rather than 'for my $line (0 .. $#{$data{$st}}){ print "\t$data{$st}->[$line]"; }', that loop becomes simply 'for (@{$data{$st}}){ print "\t$_"; }'.

      Update^2: Whoops, I missed the fact that the keys were supposed to be at the beginning of the line. Fixed the regex.

      
      -- 
      Human history becomes more and more a race between education and catastrophe. -- HG Wells