Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Logic problem

by toadi (Chaplain)
on Nov 26, 2001 at 15:34 UTC ( [id://127522] : perlquestion . print w/replies, xml ) Need Help??

toadi has asked for the wisdom of the Perl Monks concerning the following question:

I tried several approaches, but I'm stuck :(
&write($firstline); foreach $do ( keys %doing) { DO DB query for $do where fo $do can be serveral bodylines; &write($bodyline); } &write($lastline); sub write { my $line = shift; open(FILE,">>$basepath/$filename") or die; print FILE $line . "\n"; close FILE; }
Ok I know this is crappy code, but I want to illustrate my logic problem.
The filename should be $do_Timestamp. The firstline and lastline should only occur once and the body can be more lines therefor the foreach. But I only know the filename in the loop...

--
My opinions may have changed,
but not the fact that I am right

Replies are listed 'Best First'.
Re: Logic problem
by trantor (Chaplain) on Nov 26, 2001 at 16:10 UTC

    Since you get to know the filename in the loop, you could simply store your lines in a string, then write it at once when you exit the loop. This is also much more efficient than opening the file each time for writing, also less prone to concurrency problems.

    Example:

    my $buffer = "first line\n"; foreach my $do (keys %doing) { # DO DB query for $do where fo $do can be serveral bodylines; $buffer .= $bodyline . "\n"; } $buffer .= "last line\n"; # now you know the file name open FILE, ">$name" or die "bla bla"; print FILE $buffer; close FILE;

    -- TMTOWTDI

Re: Logic problem
by busunsl (Vicar) on Nov 26, 2001 at 16:14 UTC
    Define $basepath and $filename outside of the loop.
    my ($basepath, $filename, $first_written);
    Inside the loop use something like:
    $basepath = 'somewhere'; $filename=localtime; do {&write($firstline, $basepath, $filename), $first_written++} unless + $first_written; . . .
    And after the loop $basepath and $filename will still have their values, so you can just call &write($lastline, $basepath, $filename)
Re: Logic problem
by guha (Priest) on Nov 26, 2001 at 15:55 UTC
    The only problem I can see is that your open fails, possibly due to that $basepath or $filename does not contain what you expect. Are they global vars or my'ed ??

    Update: Rereading your post I see that you only have $filename inside the loop which explains why the open fails. Why is this so ?

Re: Logic problem
by hotshot (Prior) on Nov 26, 2001 at 15:52 UTC
    what is the question ?

    Hotshot