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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|