in reply to How do I split a file by lines into smaller files

If you read all lines into an array, you can use a list slice or splice to pull out chunks of text:
open(INFILE, $filename) or die "Can't open $filename: $!"; my @lines = <INFILE>; my @chapters; $chapters[1] = @lines[0 .. 55]; $chapters[2] = @lines[56 .. 112];
There are more idiomatic ways to do that, but it'll get you started.

Update: merlyn's right. That's what happens when you switch approaches while typing out your code. If you don't want to use references, do instead:

@chapter1 = @lines[0 .. 55]; @chapter2 = @lines[56 .. 112];
In general, I'd discourage that approach, because appending numbers to variable names is a warning sign. In this case, it's not a big deal.

Replies are listed 'Best First'.
Re: Re: How do I split a file by lines into smaller files
by merlyn (Sage) on Mar 06, 2001 at 06:48 UTC
    $chapters[1] = @lines[0 .. 55]; $chapters[2] = @lines[56 .. 112];
    Ooops... you're slipping. You need an extra anon-array constructor there:
    $chapters[1] = [@lines[0 .. 55]]; $chapters[2] = [@lines[56 .. 112]];

    -- Randal L. Schwartz, Perl hacker

Re: Re: How do I split a file by lines into smaller files
by BrotherAde (Pilgrim) on Mar 06, 2001 at 06:36 UTC
    Seems pretty straightforward:
    open (INFILE,$filename) or die "a slow, suffocating death: $!"; $segment=1; ENDLESS: while (1) { open (OUTFILE,">".$filename.$segment.$extension); foreach (1..56) { $line=<INFILE> or end ENDLESS; print OUTFILE $line; } close OUTFILE; $segment++; }
    The variable names should be pretty self-explanatory. Hope that helps, Brother Ade