in reply to How do I split a file by lines into smaller files
Here's another way to split one large HTML page down into smaller 56-line pages:
#!/usr/bin/perl -w use strict; use constant CHAPTER_LENGTH => 56; open INFILE, "< $ARGV[0]" or die "Could not open file $ARGV[0]: $!"; my $page = 1; until(eof INFILE) { open OUTFILE, "> chapterx_page_$page.html" or die "Could not open file chapter_$page: $!"; while(<INFILE>) { print OUTFILE; last unless $. % CHAPTER_LENGTH; #will return true when the line #no. is equally divisible by 56 } ++$page; }
This will iterate over each line in <INFILE>, and on every 56th line, it will start a new chapter. The last chapter will be 56 lines or less.
If your file size ever gets large I would suggest using this method. Reading a large file into an array, then slicing the aray after, will be more expensive than iterating over the source file one line at a time.
|
|---|