Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Split and print hash based on regex

by Cristoforo (Curate)
on Mar 27, 2018 at 20:10 UTC ( #1211875=note: print w/replies, xml ) Need Help??


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!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1211875]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2020-09-27 17:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If at first I donít succeed, I Ö










    Results (142 votes). Check out past polls.

    Notices?