Easy data persistence with JSON in Perl
#!/usr/bin/env perl
use warnings;
use strict;
use local::lib "~";
use JSON;
# Load the existing data from persistence.json, if present:
my $psjsonfile = "persistence.json";
my $persistence = {}; # empty hashref, used if the persistence file doesn't yet exist
if(-e $psjsonfile) {
open(PSIFILE, $psjsonfile) or die "Error: Unable to open $psjsonfile: $!\n";
# $/ is a special variable that holds the delimiter (usually '\n').
# Perl will continue reading from the file until it hits the delimiter;
# by declaring (but not defining) it in a local {} block, $/ is undef
# and Perl will read until the end of the file, storing the entire contents
# in the scalar $psinpuit:
my $psinput = do {local $/; <PSIFILE> };
$persistence = decode_json $psinput;
}
# Do some work with the hashref of data loaded from the JSON persistence file:
$persistence->{'new_key'} = 'new_value';
# Overwrite the JSON persistence file with a JSON representation of the
# current contents of the hashref:
open(PSOFILE, ">" . $psjsonfile) or die "Unable to write to $psjsonfile: $!\n";
print PSOFILE $persistence_json_output;
close PSOFILE;
Comments
Post a Comment