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:
sub DoIHaveThisData { my ($hash, $key) = @_; return exists $hash->{$key}; }
— Ken
In reply to Re: Use a Serialized Hash... When It Might Not Exist?
by kcott
in thread Use a Serialized Hash... When It Might Not Exist?
by redapplesonly
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |