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

What's wrong with this:
#!/usr/bin/perl -w use strict; my %files; while (<DATA>) { $_=~/^(\w+): (\d) (\w+)/; unless ($files{$1}) { open $files{$1}, ">$1.tmp" || die "Couldn't +open $1.txt...\n"; } print $files{$1} "$2 $3\n"; # No dice! (syntax error) }
The files do get created. I tried IO::File to create the handle but it is the same deal; I've used scalars this way before so way not a hash element?

Replies are listed 'Best First'.
Re: hash element as file handle
by jwkrahn (Abbot) on Mar 28, 2009 at 19:42 UTC

    Change that to:

    my %files; while ( <DATA> ) { next unless /^(\w+): (\d) (\w+)/; unless ( fileno $files{ $1 } ) { open $files{ $1 }, '>', "$1.tmp" or die "Couldn't open $1.txt. +..\n"; } print { $files{ $1 } } "$2 $3\n"; }
      print { $files{$1} } works, as does using a temp scalar (my $tmp = $files{$1}; print $tmp "...).

      Thanks!
Re: hash element as file handle
by FunkyMonk (Bishop) on Mar 28, 2009 at 23:37 UTC
    There's always print's documentation:

    Note that if you're storing FILEHANDLEs in an array, or if you're using any other expression more complex than a scalar variable to retrieve it, you will have to use a block returning the filehandle value instead:
    print { $files[$i] } "stuff\n"; print { $OK ? STDOUT : STDERR } "stuff\n";
Re: hash element as file handle
by trwww (Priest) on Mar 29, 2009 at 18:43 UTC

    Hello,

    You can always use object notation, too:

    $files{$1}->print("$2 $3\n")

    regards,