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.