Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: How do you save a perl script?

by Adam (Vicar)
on Mar 24, 2001 at 07:20 UTC ( [id://66821]=note: print w/replies, xml ) Need Help??


in reply to How do you save a perl script?

Don't.
Instead, save the variable to a separate state file using Data::Dumper, then eval it back into your program. This is rather common, actually. I wrote a package once to create an OO persistent symbol table, I don't have it handy, but here is some basic (non-OO and un-tested) code to start from:
use strict; my $persistentVar = $defaultvalue; if( -e $persistentStateFile ) { open FH, $persistentStateFile or die "Failed to open '$persistentStateFile': $!"; local $/, $@; my $ps = <FH>; eval $ps; die $@ if $@; } END{ open FH, "> $persistentStateFile" or warn "Failed to open '$persistentStateFile': $!" and exit(1); print FH Data::Dumper->Dump( [$refToPersistentVar], ['nameofpersiste +ntvar'] ) or warn "Failed to print persistent data, $!" and exit(1); close FH or warn "Failed to close $persistentStateFile, $!" and exit(1); }
However, if you really wanted to replace the currently running script on exit, then do something like:
END { open FH, "< $0" or warn "Failed to preserve state... couldn't open + '$0', $!" and exit(1); local $/; $_ = <FH>; s/my \$var=$oldvalue/my \$var=$var/m; open FH, "> $0" or warn "Failed to preserve state... couldn't writ +e to '$0', $!" and exit(1); print FH $_; close $file; }
I don't know if that would work, I wouldn't even try. But if you want, go for it.

Replies are listed 'Best First'.
Re: How do you save a perl script?
by Dominus (Parson) on Mar 25, 2001 at 19:52 UTC
    Says Adam:
    Don't. Instead, save the variable to a separate state file using Data::Dumper, then eval it back into your program.
    Holy cow. Dude, it's a counter file. It's just a number. What for you have to use Data::Dumper?

    Wowsers, talk about using a sledge hammer to squish a mosquito!

      Yup. But I'm not interested in the "How do I save a counter" problem. I'm interested in the more generic "How do I save state" problem. I s'pose I should have specified that. Sorry.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-19 03:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found