in reply to filehandle in an array
Hello bestfa, and welcome to the Monastery!
Please put your code in <code> tags — see Markup in the Monastery
If you’re reading the input file line-by-line, you’ll want to create filehandles on the fly, one for each unique data type. And when you open each output file, you’ll have to open it for appending (>>), not writing (>), to allow successive iterations of the loop to add new entries to the end of the file.
The data structure you need is a hash, not an array. Specifically, a hash that maps output file names data types to their corresponding filehandles. Then you can use Perl’s built-in exists function on the hash to determine whether a given data type already has an associated filehandle. Here is how I would approach this task:
#! perl use strict; use warnings; my $in_file = 'input.txt'; my %out_files; open(my $in, '<', $in_file) or die "Cannot open file '$in_file' for reading: $!"; while (my $line = <$in>) { my ($datum, $type) = split ' ', $line; unless (exists $out_files{$type}) { my $filename = $in_file . $type . '.txt'; open(my $fh, '>>', $filename) or die "Cannot open file '$filename' for appending: $!"; $out_files{$type} = $fh; } print { $out_files{$type} } $datum . "\n"; } for (keys %out_files) { close $out_files{$_} or die "Cannot close the '$out_files{$_}' output file: $!"; } close $in or die "Cannot close file '$in_file': $!";
Update: Fixed die message for closing output files; also corrected fourth paragraph.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: filehandle in an array
by bestfa (Novice) on Feb 23, 2016 at 03:49 UTC |