Serializing Complex Data Structures

By: w1ldc4rd-w1z4rd
[ BACK... ]

While Data::Dumper is commonly used for debugging, it’s also a powerful tool for serializing and deserializing complex data structures. Here’s how you can use it to create snapshots of your data, save them to files, and restore them later:

Example Script

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use Data::Dumper;

# Configure Data::Dumper
$Data::Dumper::Purity   = 1;  # Produce output that's valid as Perl code
$Data::Dumper::Indent   = 1;  # Turn on pretty-printing with a single-space indent
$Data::Dumper::Sortkeys = 1;  # Sort hash keys for consistent output
$Data::Dumper::Terse    = 1;  # Avoid outputting variable names (just the structure)

# Create a complex hash
my $complex_hash = {
    numbers => [1, 2, 3, 4, 5],
    nested => {
        a => 'apple',
        b => 'banana',
        c => [qw(cat dog bird)],
    },
    data => {
        name => 'John Doe',
        age => 30,
        hobbies => ['reading', 'cycling', {chess => 'advanced'}],
    },
};

# Serialize and save to file
my $file = 'complex_hash.txt';
open my $fh, '>', $file or die "Cannot open $file: ";
print $fh Dumper($complex_hash);
close $fh;

# Clear the original hash
undef $complex_hash;

# Restore the hash from file
my $restored_hash;
$restored_hash = do "./$file" or die "Cannot load ./$file: ";

# Verify the restored hash
say "\nRestored hash:";
say Dumper($restored_hash);

# Use the restored hash
say "A nested value: " . ($restored_hash->{nested}{b} // 'undef');
say "Third hobby: " . ($restored_hash->{data}{hobbies}[2]{chess} // 'undef');

Output

Content of complex_hash.txt:

Restored hash:
{
  'data' => {
    'age' => 30,
    'hobbies' => [
      'reading',
      'cycling',
      {
        'chess' => 'advanced'
      }
    ],
    'name' => 'John Doe'
  },
  'nested' => {
    'a' => 'apple',
    'b' => 'banana',
    'c' => [
      'cat',
      'dog',
      'bird'
    ]
  },
  'numbers' => [
    1,
    2,
    3,
    4,
    5
  ]
}

A nested value: banana
Third hobby: advanced

Closing Thoughts

This script demonstrates how to serialize a complex hash, save it to a file, and then restore it. The restored data can be used just like the original structure. This technique is useful for caching, creating configuration files, or saving application states.

While Data::Dumper is great for quick serialization, consider more efficient methods like Storable or JSON for large datasets in production environments.

Copyright ©️ 2024 perl.gg