
FishMonger
Veteran
Feb 25, 2012, 6:41 AM
Views: 1211
|
|
Re: [hem] Help in getting filename from file handle
|
|
|
1) Use a hash to store the filehandles instead of an array. 2) Use a lexical var for the filehandle instead of a bareword 3) Use the 3 arg form of open 4) Don't use the C style for loop, it's very messy. 5) Don't use titlecase var names like that. Instead, separate the words with an underscore to increase readability.
my @log_files = qw( file1 file2 file3 ); my %file_handle; foreach my $filename ( @log_files ) { open $file_handle{ $filename }, '<', $filename or die "Can't open '$filename' for reading <$!>"; } foreach my $filename ( keys %file_handle ) { print "Name of File to read next is: $filename\n"; while (my $line = <$file_handle{ $filename }> ) { # process file } close $file_handle{ $filename }; } If you need to loop over the handles in the same order in which they were opened, then you can either loop over the array instead of the hash keys, or use the Tie::IxHash module which retains the order. http://search.cpan.org/~chorny/Tie-IxHash-1.22/lib/Tie/IxHash.pm
(This post was edited by FishMonger on Feb 25, 2012, 6:48 AM)
|