use strict; use warnings; my $source ="temp.txt"; my $num = 1; my $recline = 10; open(DATA,"<$source") or die "Can't open '$source' $!"; while (!eof DATA) { my $outfile=sprintf("Int_%s.txt",$num); ## Open the file once every iteration open OUT, ">$outfile"; my $header = sprintf("%-1s%-12s%-8s%-4s%-4s%-10s%-33s","H",$outfile,"20101221","1230","$num","$recline"," "); print OUT $header ."\n"; ## Prints the header here ### Print the contents of the file here, the header is printed above and trailer is printed below. #### for (1 .. $recline) { last if eof DATA; last if ! defined (my $line = ); print $line; } my $trailer = sprintf("%-1s%-12s%-8s%-4s%-4s%-10s%-33s","T",$outfile,"20101221","1230","$num","$recline"," "); print OUT $trailer ."\n"; ## Prints the trailer here $num++ if ($. % $recline eq '0'); close (OUT); ## Close the file in the same iteration, so that a new file is opened next iteration } close(DATA);