in reply to filehandle in an array

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:

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

— Ken