{ # note the {} brackets. This concerns the scope of the next line. local $/; # sets $/ = undef for this block only. open FH, $infile or die $!; $_ = ; # Reads the entire file into memory. close FH or die $!; @_ = m/(some-regex-for-the-block)/gm; } # now @_ contains an array of matches for the regex. # write each one to a different file: my $filenum = 0; for( @_ ) { ++$filenum; open FH, ">MATCH$filenum" or die "Failed to open MATCH$filenum, $!"; print FH $_, $/; close FH or die $!; }