G'day redapplesonly,
"I am working on a Perl (v5.30.0) script that needs to use stateful information from the previous run of the script."
All of your steps, and other design notes, seem spot-on to me. :-)
"But here's the problem: What about the first time the script runs?"
That's a very valid point.
I don't use Storable very often, but when I do I encounter the same issue.
I usually handle this by dealing with it before runtime execution starts
in an INIT block.
Here's a rough example of how I might have written your code (pm_11148149_storable_first_run_0.pl):
#!/usr/bin/env perl
use 5.030;
use warnings;
use Storable;
my ($hashfile, $serial_data_for);
INIT {
$hashfile = 'pm_11148149_storable_first_run.sto';
$serial_data_for = -e $hashfile ? retrieve($hashfile) : {};
}
my @keys = qw{key1 key2 key3};
my @vals = qw{data1 data2 data3};
$serial_data_for->@{@keys} = @vals;
store($serial_data_for, $hashfile);
I added some extra statements for reporting/demo purposes (pm_11148149_storable_first_run_1.pl):
#!/usr/bin/env perl
use 5.030;
use warnings;
use Storable;
use Data::Dump;
warn "Perl version: $^V\n";
my ($hashfile, $serial_data_for);
INIT {
$hashfile = 'pm_11148149_storable_first_run.sto';
$serial_data_for = -e $hashfile ? retrieve($hashfile) : {};
}
say 'Serialised data:';
dd $serial_data_for;
my @keys = qw{key1 key2 key3};
my @vals = qw{data1 data2 data3};
$serial_data_for->@{@keys} = @vals;
store($serial_data_for, $hashfile);
Here's some equivalent output to your sample run:
ken@titan ~/tmp
$ rm pm_11148149_storable_first_run.sto
ken@titan ~/tmp
$ ls -l pm_11148149_storable_first_run.sto
ls: cannot access 'pm_11148149_storable_first_run.sto': No such file o
+r directory
ken@titan ~/tmp
$ ./pm_11148149_storable_first_run_1.pl
Perl version: v5.30.0
Serialised data:
{}
ken@titan ~/tmp
$ ls -l pm_11148149_storable_first_run.sto
-rw-r--r-- 1 ken None 69 Nov 12 13:00 pm_11148149_storable_first_run.s
+to
ken@titan ~/tmp
$ ./pm_11148149_storable_first_run_1.pl
Perl version: v5.30.0
Serialised data:
{ key1 => "data1", key2 => "data2", key3 => "data3" }
ken@titan ~/tmp
$
Notes:
-
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.