I was trying to do something similar to the UNIX split command. I am reading through a file and splitting the lines randomly between several output files. The number of output files is determined at run time by a UNIX environment variable.
I was trying to do it by maintaining a line count and then using modulus of that with the number of output files to determine which file to write to. The problem is with how to set up an array of file names and write to the correct one using a variable file handle.
So far I've got:
This opens the files correctly, but the write dumps data only to the last opened file.
I was trying to do it by maintaining a line count and then using modulus of that with the number of output files to determine which file to write to. The problem is with how to set up an array of file names and write to the correct one using a variable file handle.
So far I've got:
Code:
#!/usr/bin/perl
$no_part=$ENV{'_partitions'};
open(INPUT, $ENV{'_inputFile'});
for ($i=1; $i <= $no_part; ++$i)
{
$output[$i] = "filehandle";
$FilePath = "$ENV{'_outputFileStub'}" . "$i";
open($output[$i], ">$FilePath") or die $!;
}
# set line counter
$lc = 1;
while ($line = <INPUT>)
{
chomp($line);
$modval=($lc % $no_part)+1;
$outfile=$output[$modval];
print $outfile $line, "\n";
print $modval, "\n";
++$lc;
}
close(INPUT);
This opens the files correctly, but the write dumps data only to the last opened file.