Maire has asked for the wisdom of the Perl Monks concerning the following question:
Good afternoon all,
I have a hash containing thousands of lines of text from hundreds of different files. Every time a certain phrase appears in the hash (in the SSCCE below, "This is"), I want to create a new txt file which prints both the phrase and all subsequent text until we reach the next "This is".
So, for instance, I had hoped that the script below would create six text files (named UserA_1, UserA_2 etc.) where the first file contained the text "This is line 1 from text 1 another line here which should be included in the text file with the above line.", the second file contained the text "This is line 2 from text 1", and so on.
However, although the script below creates the 6 new text files (and names them appropriately), it does not actually print anything into the files.#!/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 a +bove 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 a +bove 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} $_; } }
I have been working on this script for nearly a week, but I can't spot my mistake(s), and thus I would be very grateful for any help.
EDIT:my $count = 1; my $outfile; while (<DATA>) { 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 a +bove 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 a +bove line. This is line 3 from text 2
|
|---|