Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^3: Merging files

by mirod (Canon)
on Apr 11, 2005 at 08:45 UTC ( [id://446529]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Merging files
in thread Merging files

I think you should keep track of which filehandle is still open, and read it only in that case. And I am always wary of while(1) loops. But its probably just me ;--)

#!/usr/bin/perl -w use strict; use Fatal qw(open close); my @files= @ARGV; my %fh; # file => file handle foreach my $file (@files) { open( my $fh, '<', $file); $fh{$file}= $fh; } while( keys %fh) { foreach my $file (@files) { if( exists $fh{$file}) { my $fh= $fh{$file}; if( defined( my $line= <$fh>)) { chomp $line; print $line;} # regular line else { delete $fh{$file}; } # eof reached for this file } } print "\n"; # end of line for all files }

Replies are listed 'Best First'.
Re^4: Merging files
by sk (Curate) on Apr 11, 2005 at 09:23 UTC
    Thanks again! Now i understand the undef issue. Also thanks for the one-liner, showed me how to use Dumper!!!

    Mirod, I agree, it is definitely better to keep track of filehandles and close them when they run of out data!

    Learnt a few nice things today :)

Re^4: Merging files
by cazz (Pilgrim) on Apr 11, 2005 at 14:26 UTC
    I agree, while(1) loops can be bad. I'm fond of doing something similar to what you are doing instead of while(1). I have spent much more time than I care to remember debugging code that was due to poor while(1) implementations.

    I have a few minor nits to pick with your example.

    1. You don't close any of your file handles. Why keep em around once you are done? I would inject a close right before your delete
    2. Intead of repeatedly checking every file in the list you are processing, why not just check the list of files currently open? The foreach my $file (@files) loop is easy to swap out with a foreach my $fh (keys %fh)

    The change would look something like this:

    while (keys %fh) { foreach my $fh (keys %fh) { if (defined(my $line = <$fh>)) { chomp $line; print $line; } else { close($fh); delete($fh{$fh}); } } }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://446529]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2024-04-26 00:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found