#!/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; while ($mycorpus{$filename} =~ /This is/g) { close $outfile if $outfile; open $outfile, '>', "UserA_$count.txt" or die "could not open"; $count++; print {$outfile} $_; } } #### my $count = 1; my $outfile; while () { if ( my($regex) = /This is/g) { close $outfile if $outfile; open $outfile, '>', "UserA$1_$count.txt" or die "could not open 'UserA$regex.txt' $!"; $count++; } print {$outfile} $_; } __DATA__ 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 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