G'day bestfa,
Welcome to the Monastery.
"... the number of output files can vary according to data ..."
In that case, I'd only open files on demand.
"But this code didn't make an error message ..."
Perl will provide you with diagnostics if you ask it.
Always put these two lines at the start of all your code:
use strict;
use warnings;
See strict and warnings for details.
You should also check your I/O operations.
You can do this manually but its time-consuming and error-prone:
just let Perl do it for you (with the autodie pragma) by adding this line:
use autodie;
"... and didn't produce output files."
You didn't declare or populate @filename_array.
You also didn't attempt to write any output data.
In addition, also note:
-
You didn't declare or populate @data_type_array.
-
@filehandle_array=@data_type_array; is almost certainly wrong.
-
These long-winded, C-like lines of code:
$data_type_number=@data_type_array;
for($i=0;$i<$data_type_number;$i++)
{
...
}
Can be written far more succinctly with this Perl-like code:
for (0 .. $#data_type_array) {
...
}
-
The use of global variables throughout your code is a disaster waiting to happen.
Prefer lexical variables, and control their scope, for far less error-prone code.
More information on the points I've raised can be found in perlintro.
Each section has links to further discussion and advanced usage: follow as required.
Your idea of storing filehandles in a data structure is fine;
however, your code is problematic (and incomplete).
Here's how I might have approached this task:
#!/usr/bin/env perl -l
use strict;
use warnings;
use autodie;
use constant {
FILENAME => 0,
FILEHANDLE => 1,
};
my %file = (
animal => [ 'pm_1155794_animal.txt' ],
plant => [ 'pm_1155794_plant.txt' ],
goods => [ 'pm_1155794_goods.txt' ],
);
while (<DATA>) {
my ($item, $type) = split;
print { get_fh($type) } $item;
}
sub get_fh {
my $type = shift;
open $file{$type}[FILEHANDLE], '>', $file{$type}[FILENAME]
unless defined $file{$type}[FILEHANDLE];
return $file{$type}[FILEHANDLE];
}
__DATA__
cat animal
apple plant
strawberry plant
muffler goods
The following, simple checks show this worked:
$ cat pm_1155794_animal.txt
cat
$ cat pm_1155794_plant.txt
apple
strawberry
$ cat pm_1155794_goods.txt
muffler
|