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:
Help in getting filename from file handle

 



hem
User

Feb 24, 2012, 10:19 PM

Post #1 of 3 (1409 views)
Help in getting filename from file handle Can't Post

@LogFilesNames is the array of names of files I have to open and read

for (my $Count = 0;$Count < scalar(@LogFilesNames ) ; $Count++)
{
local *FILE;
# print "OPening $LogFilesNames[$Count]\n";
open FILE, $LogFilesNames[$Count] or die "Cannot open $LogFilesNames[$Count] for read :$!";
#push the typeglobe to the end of the array
push(@Filehandles, *FILE);
# print "Num FIles = $Count\n";
}


foreach my $handle (@Filehandles)
{
while (<$handle>) ## Start Reading File
{
###### HOW CAN I TELL THE FILE NAME HERE
print "Name of File read is ?????
}
}

How can i find the name of the file from file handler

I understand that it should be in the order its input in array at line 7 but i am looking for a cleaner way to find it

Code



      
    


FishMonger
Veteran / Moderator

Feb 25, 2012, 6:41 AM

Post #2 of 3 (1378 views)
Re: [hem] Help in getting filename from file handle [In reply to] Can't Post

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)


hem
User

Feb 29, 2012, 9:56 AM

Post #3 of 3 (1326 views)
Re: [FishMonger] Help in getting filename from file handle [In reply to] Can't Post

Got it Thanks for your help . Appreciate it

 
 


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

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