in reply to Split and print hash based on regex

Considering you use the word "split" in the title of your post, it's funny you aren't using split to process the text.
our $all_text = join "", <ARGV>; # files, STDIN, etc. our $key_phrase = "This is "; # should not be hard-coded our $base_name = "UserA_"; our $ext = ".txt"; our @bits = split m/\Q$key_phrase\E/, $all_text; # if line 1 data includes the key phrase, element 1 will be empty: shift @bits if $all_text =~ m/^\Q$key_phrase\E/; my $count = 1; foreach my $bit (@bits) { # suggest padding the index number so files sort correctly my $filename = sprintf "%s%2.2d%s", $base_name, $count++, $ext; open FILE, ">", $filename or die "Could not write to \"$filename\": $!\n"; print FILE "$key_phrase$bit"; # put back the what split() excised close FILE; }
This solution assumes that you can read all the data into memory, of course, but unless it's a million lines or an ongoing TCP/IP connection or something, I rarely have issues with that.

Replies are listed 'Best First'.
Re^2: Split and print hash based on regex
by Maire (Scribe) on Mar 28, 2018 at 07:26 UTC
    Thanks for this. I've never (successfully!) worked with the split function before, but your script exemplifies it in a way that I (as a relative newbie) can understand, thanks!