Hi folks,
I have a file which has the following format
245
record #1
record #2
.
.
record #245
====
165
record #1
record #2
.
.
record #165
====
As you can make out, the first line is the number or records in that set (till "===="). There are 20 such records. Instead of regexing, I used the following
#initialize some variables
my $records; # No. of records
my $last; # The last line
my $ini = 1; # set initial line
my $count = 1; # counter
for (my $count = 1; $count <= 20; $count++){
open (OLD, "< $old_file.txt") || die $!; # open file
# Now we need to split up the file into 20 files
open (NEW, "> $old_file$count.txt") || die $!; #open outputfile
while (<OLD>){
if($. == $ini){
chomp;
$records = $_;
}
}
close OLD;
$last = $ini + $records + 1;
open (OLD, "<$old_file.txt") || die $!; # I am more comfortable with r
+e-opening the file like this
while (<OLD>){
next unless $. >= $ini;
print NEW $_;
last if $. >= $last;
}
close OLD;
close NEW;
$ini = $last + 1;
}
What I wanted to know was, that in a case like this, would it be better practise to use a regex (since there are well-defined patterns), or use, what to me at least, is a simpler approach.
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'
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.