http://qs321.pair.com?node_id=1211875


in reply to Split and print hash based on regex

Here is a possible solution that makes use of the three argument open (with a reference to the filename). This if all the data is in a hash.
#!/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; 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; } }
Edit: added conditional to print command ('if $outfile')

Edit2: The solution offered by tybalt89, Re: Split and print hash based on regex is better than this one. His does not rely on the identifying phase to be at the front of the line of text. The post by jh also is better than this one.

Replies are listed 'Best First'.
Re^2: Split and print hash based on regex
by Maire (Scribe) on Mar 28, 2018 at 07:36 UTC
    Ah, very nice solution, thanks! I wasn't aware that one could "open" part of a hash in this way: that tip will save me a lot of time in the future!