CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [hem] Help in getting filename from file handle: Edit Log



FishMonger
Veteran / Moderator

Feb 25, 2012, 6:41 AM


Views: 1307
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.


Code
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)


Edit Log:
Post edited by FishMonger (Veteran) on Feb 25, 2012, 6:48 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives