How to write on different output files at each iteration of loop? (Perl) -
i have hash of hashes of hashes in perl called data
first level keys: f, nf , s (basically, %data={'f' => ..., 'nf' => ..., 's' => ...}
)
at beginning of code open 3 output handles:
open (my $fh1, ">>", $filename1) or die "cannot open > $filename1: $!"; open (my $fh2, ">>", $filename2) or die "cannot open > $filename2: $!"; open (my $fh3, ">>", $filename3) or die "cannot open > $filename3: $!";
then, while code runs, populates hash of hashes of hashes and, @ end, want print resulting hash of hashes each key 'f', 'nf' , 's' separate file (identified 3 file handles have defined in beginning.) i'm not sure how this. have tried following: right before foreach
loop in print hash, have defined
my @file_handles=($fh1, $fh2, $fh3); $handle_index=0;
and in each iteration of hash write file using
print $file_handles[$handle_index] "$stuff\n";
however, when try run code, tells me string found operator expected
it's understanding i'm not telling him correctly file handle should use. suggestions?
i seem able replicate problem using file handle stored in array. perhaps not possible, though have sworn have seen used before.
>perl -lwe"open $x, '>', 'a.txt' or die $!; @x = ($x); print $x[0] 'asd';" string found operator expected @ -e line 1, near "] 'asd'" (missing operator before 'asd'?) syntax error @ -e line 1, near "] 'asd'" execution of -e aborted due compilation errors.
the same goes using hash. possible workarounds be:
you can skip indirect object notation , use:
$file_handles[$index]->print("$stuff\n")
or can use perl-style loop instead print:
for $fh (@file_handles) { print $fh "$stuff\n"; }
indirect object notation when put object -- in case file handle -- before function call, so:
my $obj = new module;
instead of traditionally:
my $obj = module->new;
more information indirect object notation in perldoc perlobj
Comments
Post a Comment