in reply to Re: Dynamic File Handles
in thread Dynamic File Handles

I understand that part. But what I need is the file handle to be dynamic Basically I want to beable to have a random set of files all open at the same time for a specific set of data mashing and mangling. So I want to beable to specify which files to have open, and the script opens them all at the same time
@files =qw (file1 file2 file3 file4); foreach(@files) { open ($fh, "$_"); while(<$fh>) { ... } close($fh); }
$fh will be a random string generated during each loop Yes, what I am doing is stupid. I know that much :-) But its for a dirty dirty piece of code. I dont want to have to keep opening and closing files. Thanks!

Replies are listed 'Best First'.
Re^3: Dynamic File Handles
by cmeyer (Pilgrim) on Jun 06, 2005 at 20:54 UTC

    Here's a subroutine that will return a hashref, where the keys are the filenames passed in (for those that it is able to open), and the values are filehandles.

    updated: removed extraneous "my $fh"

    sub open_files { my @files = @_; my %file_handles; for my $file ( @files ) { if ( open my $fh, '<', $file ) { $file_handles{ $file } = $fh; } else { warn "couldn't open $file for reading: $!\n"; } return \%file_handles; }