Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^2: Only last record is written to the output file instead of all records

by valavanp (Curate)
on Nov 17, 2008 at 06:49 UTC ( #724011=note: print w/ replies, xml ) Need Help??


in reply to Re: Only last record is written to the output file instead of all records
in thread Only last record is written to the output file instead of all records

If i have the files open before the loop the files will be created automatically without satisfying the condition. For e.g if i have only 5 records, it will create 3 files. All the 5 records will be written to the first file and leaving other files blank without any content.


Comment on Re^2: Only last record is written to the output file instead of all records
Re^3: Only last record is written to the output file instead of all records
by davido (Archbishop) on Nov 17, 2008 at 07:29 UTC

    Test for the condition prior to entering the loop, OR, open within the loop, but on each iteration check to see if the file is already open. Easy way to do that would be to use a lexical filehandle, scoped to just outside the loop. Here's an example:

    { my $fh; while ( ....condition.... ) { unless( defined( $fh ) ) { open $fh, '>', $filename or die $!; } # ....do your stuff... } close $fh or die $!; }

    Dave

      Better to use fileno to test filehandles as a filehandle can be defined and closed:

      $ perl -le' print defined $FH ? "defined" : "not defined"; print fileno $FH ? "open" : "not open"; open my $FH, "<", "test.txt" or die "test.txt: $!"; print defined $FH ? "defined" : "not defined"; print fileno $FH ? "open" : "not open"; close $FH; print defined $FH ? "defined" : "not defined"; print fileno $FH ? "open" : "not open"; ' not defined not open defined open defined not open

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (15)
As of 2014-09-02 16:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (25 votes), past polls