Easy data persistence with JSON in Perl

Dumping this here because it took me a minute to get back up to speed with everything Perl (I’ve forgotten most of what I used to know, regarding things like hash and array references, etc, but with just a little bit of playing around it’s all coming back). This stores a Perl hash (well, actually, a hashref) in a JSON file.

Voila, you’ve got a JSON file with the contents of the hashref. JSON will have to be installed from CPAN if it’s not already (which I did as an unprivileged user using local::lib).

#!/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