my $page = ''; while (<>) { if ( /xxx PAGE BOUNDARY \d+ xxx/ ) { output( $page ); $page = ''; next; } $page .= $_; }