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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.