in reply to can't write a variable to a file

Can you show the code that sets $savestr and calls Savetofile()? I suspect that $savestr is not a global variable and the Savetofile function isn't in it's scope.

Replies are listed 'Best First'.
Re: Re: can't write a variable to a file
by aquarium (Curate) on May 11, 2004 at 09:20 UTC
    as per docs...you never unlock a file..just close it and it becomes unlocked and is flushed. unlocking before close (where it's flushed) is causing the problem....especially that you don't write "\n", which forces a buffer flush also.
      I've written it with out the lock, and it still causes the problem.
Re: Re: can't write a variable to a file
by sabotodd (Initiate) on May 11, 2004 at 10:12 UTC
    The variable is not contained in any subs. I've tried just holding: $savestr="hello!" and it still doesn't work.
    but if I pass "hello!" directly, it works.
    $savestr="$optionstr\n$total\n$countstr"; print $savestr; #save data back to file #save edited data back to file ####################save file sub Savetofile{ #open and read each line open(OUTFILE,">../kicks.txt")or die("Cannot open file"); flock(OUTFILE, LOCK_EX); print (OUTFILE "$savestr"); flock(OUTFILE, LOCK_UN)or die("Cannot unlock file"); close (OUTFILE) or die("Cannot close file"); }

    Edited by Chady -- added code tags.

      a subroutine doesn't get executed unless you call it; this:
      print "a"; sub doit { print "zed" } print "b"; &doit();
      prints "a", then "b", then "zed". After the print "a", perl jumps right over the sub definition to the next plain statement.
        ok..I know how to run subroutines. I am calling the routine near the top of the file (to keep things organized). This code works when I call the sub. However, it only runs when a string is outputted e.g. "hello" not $hello="hello"..that's the issue here.

      You don't show where you are actually making the call to Savetofile. It needs to be somewhere after assigning to $savestr. Can you paste all the code, and explain (with examples) what you mean by 'if I pass "hello!" directly'.

      A better solution might be to pass the string as a parameter to Savetofile:

      $savestr = "whatever\n"; &Savetofile($savestr); sub Savetofile { my $string = shift; if (defined($string)) { # all the open/lock/print/close stuff goes here } }

      Also can you please put your code in <code> tags, it makes it a lot easier to read! Thanks...