use warnings; use strict; my $chunk; my $chunkSize = 40; my $matchText = 'I'; my $partCount = 1; my $fileSize = 0; while (my $newChunkSize = read (DATA, $chunk, $chunkSize)) { next if $fileSize + $newChunkSize < $chunkSize; # not a complete chunk # Have at least $chunkSize - look for a stop point my $breakPoint = index $chunk, $matchText; if ($breakPoint == -1) { $fileSize += $newChunkSize; next; # Can't change file yet } # Found a stop point, all change print substr $chunk, 0, $breakPoint, ''; # close current output file here and create the new file ++$partCount; print "\n\n***Start of new file for part $partCount\n"; $fileSize = $newChunkSize - $breakPoint; } continue { print $chunk; } __DATA__