Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

store file handles in a hash

by llancet (Friar)
on Oct 30, 2012 at 14:07 UTC ( #1001507=perlquestion: print w/replies, xml ) Need Help??
llancet has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks!

For some reason, I want to open several files for write, and seek those output handles by their name:

my %handles; while (<IN>) { my $file_out = get_the_way_out($_); my @some_data = get_the_data($_); if (!exists $handles{$file_out}) { open my $handle,'>',$file_out or die $!; $handles{$file_out} = $handle; } # but this is not allowed say $handles{$file_out} join "\t",@some_data; } close $_ foreach values %handles;

How can I properly organize my handles? Thanks for a lot!

Replies are listed 'Best First'.
Re: store file handles in a hash
by Athanasius (Chancellor) on Oct 30, 2012 at 14:14 UTC

    From print:

    If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead...

    So, just change the last line in the while loop to:

    say { $handles{$file_out} } join "\t", @some_data;

    Hope that helps,

    Athanasius <°(((><contra mundum

Re: store file handles in a hash
by trwww (Priest) on Oct 30, 2012 at 16:23 UTC
    $handles{$file_out}->say( join "\t",@some_data );

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1001507]
Approved by Athanasius
[hippo]: See also Getting Started with Perl for some gentle introductory tutorials.
[thao4]: I don't see where I can post my question. I am french so not good in English
[erix]: go to the bottom of this page: Seekers of Perl Wisdom

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (9)
As of 2018-02-21 09:59 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (276 votes). Check out past polls.