Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I have a problem. This script runs:
use 5.010; use strict; use warnings; my $Year = "2011"; my $Month = "04"; my $address = "D:/myfolder/".$Year."/".$Month."/data/"; open(SOURCE, $address."TTT.txt") || die "$!"; open(AAA, ">D:/myfolder/".$Year."/".$Month."/AAA/AAA.txt") || die "$!" +; open(BBB, ">D:/myfolder/".$Year."/".$Month."/BBB/BBB.txt") || die "$!" +; open(CCC, ">D:/myfolder/".$Year."/".$Month."/CCC/CCC.txt") || die "$!" +; open(DDD, ">D:/myfolder/".$Year."/".$Month."/DDD/DDD.txt") || die "$!" +; my @AAA; my @BBB; my @CCC; my @DDD; my @contents=<SOURCE>; close (SOURCE); my $Header = shift @contents; foreach(@contents) { when (/;AA/) {push @AAA, $_;} when (/;BB/) {push @BBB, $_;} when (/;CC/) {push @CCC, $_;} when(!/;AA/ && !/;BB/ && !/;CC/) {push @DDD, $_;} default {} } unshift @AAA, $Header; unshift @BBB, $Header; unshift @CCC, $Header; unshift @DDD, $Header; print AAA @AAA; print BBB @BBB; print CCC @CCC; print DDD @DDD; close (AAA); close (BBB); close (CCC); close (DDD);
But I tried to shorten the script with some loops. The following script brings error:
use 5.010; use strict; use warnings; use FileHandle; my $Year = "2011"; my $Month = "04"; my $address = "D:/myfolder/".$Year."/".$Month."/data/"; open(SOURCE, $address."TTT.txt") || die "$!"; my $fh; my @namen2 = qw/ AAA BBB CCC DDD /; my %fh = map {$_, $fh = FileHandle->new(">D:/myfolder/".$Year."/".$Mon +th."/".$_."/".$_.".txt");} @namen2; my @AAA; my @BBB; my @CCC; my @DDD; my @contents=<SOURCE>; close (SOURCE); my $Header = shift @contents; my %testhash = ("AAA" => \@AAA, "BBB" => \@BBB, "CCC" => \@CCC, "DDD" => \@DDD, ); foreach(@contents) { when (/;AA/) {push @AAA, $_;} when (/;BB/) {push @BBB, $_;} when (/;CC/) {push @CCC, $_;} when(!/;AA/ && !/;BB/ && !/;CC/) {push @DDD, $_;} default {} } foreach (keys %testhash) { unshift @{ $testhash{$_} }, $Header; } foreach (keys %fh) { my $x = $_; foreach (keys %testhash) { my $y = $_; if ($x eq $y) {print $fh{$x} @{ $testhash{$y}};} } } foreach (keys %fh) {close $fh{$_};}
The error message by trying hash comparison (%fh and %testhash): "Array found where operator expected" and then "syntax error". I tried this with smart match, no success either. Please help! Many thanks in advance!

Replies are listed 'Best First'.
Re: Won Doc
by toolic (Bishop) on May 05, 2011 at 16:54 UTC
    The error goes away if I change:
    if ($x eq $y) {print $fh{$x} @{ $testhash{$y}};}
    to:
    if ($x eq $y) {print {$fh{$x}} @{ $testhash{$y}};}
    Notice the extra curlies around the filehandle; see print for an explanation.
      Many thanks toolic!!!
Re: Won Doc
by Jenda (Abbot) on May 06, 2011 at 07:57 UTC
    foreach (keys %fh) { my $x = $_;
    is better written
    foreach my $x (keys %fh) {

    Jenda
    Enoch was right!
    Enjoy the last years of Rome.

      Thank you Jenda!