#!/usr/bin/perl use strict; use warnings; #SSCCE: my %mycorpus = ( text1 => "This is line 1 from text 1 another line here which should be included in the text file with the above line. This is line 2 from text 1 This is line 3 from text 1", text2 => "This is line 1 from text 2 This is line 2 from text 2 another line here which should be included in the text file with the above line. This is line 3 from text 2", ); my $count = 1; foreach my $filename (sort keys %mycorpus) { my $outfile; open my $fh, '<', \$mycorpus{$filename} or die $!; while (<$fh>) { chomp; if (/^This is/) { close $outfile if $outfile; my $out = "UserA_$count.txt"; open $outfile, '>', $out or die "could not open '$out' for writing $!"; $count++; } print $outfile $_, "\n" if $outfile; } }