A Perl program alters the outside world in some manner. Otherwise, there’d be no point in running the program. But sometimes, our Perl programs need a little “memory” to do their job, something that persists information from one invocation to the next. But how do you keep such values around?
A Perl program alters the outside world in some manner. Otherwise, there’d be no point in running the program. But sometimes, our Perl programs need a little “memory” to do their job, something that persists information from one invocation to the next. But how do you keep such values around?
If the value is simple enough, you can just write it out to a file, as this snippet does.
my $MEMORY = “memory-file”; # … at beginning of program … open M, “<$MEMORY” or die “Cannot open $MEMORY for reading: $!”; { local $/; $value = <M> } close M; # … at end of program … open M, “>$MEMORY” or die “Cannot open $MEMORY for writing: $!”; print M $value; close M;
But there are a few problems with this technique.
First, the value has to be a simple scalar. That means it’s not very interesting and you really can’t scale to multiple values by using separate files.
Second, because the program is writing the string version of the value to a file, it’ll run into slight problems storing floating point numbers accurately, simply because internal floating point numbers do not correlate with decimal strings on a precise one-to-one basis.
Third, this technique breaks down if there are multiple instances of the program using the data. For example, two programs might both read the value, then update it, then write out their respective new values back to the file. The last…
Please log in to view this content.
Not Yet a Member?
Register with LinuxMagazine.com and get free access to the entire archive, including: