in reply to To regex or not to regex

Thanks for sharing. Here is what i came up with. Instead of setting a limit at 20 records, this version will keep adding new files until the input file is exhausted.

I did use one regex to read the line that tells how many records to expect. I also took the liberty of changing the names of the output files with sprintf and a different prefix than the original file (just so i could delete my mistakes easier :D).

use strict; open(IN,'old_file.txt') or die; my $i = 1; while (<IN>) { if (/^(\d+)\s*$/) { open(OUT,'>new_file'.sprintf("%02d",$i++).'.txt') or die; do { $_ = <IN>; print OUT; } for (1..$1); } }

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re: (jeffa) Re: To regex or not to regex
by abstracts (Hermit) on Mar 11, 2002 at 06:07 UTC
    Here is a more newbie-friendly version of jeffa's code. Consider it a learning tool.
    my $file_num = 1; while (<IN>) { if (/^(\d+)\s*$/) { my $count = $1; my $fname = sprintf("new_file%02d.txt", $file_num); open(OUT,">$fname") or die "Cannot open file $fname: $!\n"; for(1..$count){ my $rec = <IN>; print OUT $rec; } close OUT; $file_num++; } else { # ignore the file separator ======= } }
Re: (jeffa) Re: To regex or not to regex
by mndoci (Scribe) on Mar 11, 2002 at 06:11 UTC

    Thank you very much. Much more compact than my blurb. There is one thing missing though, and I am sure I can fix that (I have not tried) without too much fuss. I want to include the first line (number of records), and the last line (====) as well. Otherwise, works like a charm.

    mndoci

    "What you do in this world is a matter of no consequence. The question is, what can you make people believe that you have done?"-Sherlock Holmes in 'A study in scarlet'