in reply to Dynamic File Handles

The first argument to open is suppose to be filehandle, not the name of the file you want to open. Try this instead:

use strict; use warnings; my @file = qw(foo bar baz); for (@file) { open FH, "path/to/file/$_"; print while <FH>; close FH; }

UPDATE: Those aren't dynamic file handles, by the way. You are just storing the names of the files you want to open in an array, that's all.

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

Replies are listed 'Best First'.
Re^2: Dynamic File Handles
by Anonymous Monk on Jun 06, 2005 at 20:34 UTC
    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!

      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; }