in reply to Re: can't write a variable to a file
in thread can't write a variable to a file

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.

Replies are listed 'Best First'.
Re: Re: Re: can't write a variable to a file
by ysth (Canon) on May 11, 2004 at 10:28 UTC
    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.
        Sorry, just looked like you were assuming you didn't need to call the subroutine.

        Do you call the routine before setting the variable??

Re: Re: Re: can't write a variable to a file
by muntfish (Chaplain) on May 11, 2004 at 11:04 UTC

    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...