Working with Files and Data Structures in Perl

Using Perl, you can directly save a data structure to a file.

This is a simple script I made to figure out this works. I’ve only have a hashtable of hex values, though I nested two has tables to divided up each base digits of a byte’s nibbles. This script makes use of the module Storeable and you use a nice one liner to store this hashtable.

use Storable;
%hash = (
	0 => '0x00',
	firstNibble => {	
		1 => '0x01',
		2 => '0x02',
		4 => '0x04',
		8 => '0x08'
	secondNibble =>; {
		16 => '0x16',
		32 => '0x20',
		64 => '0x40',
		128 => '0x80'

store(\%hash, 'hashStruct.bin');  # Creating a file

exit 0;

Next I made another script to try to read in my hash table and print the results. One note though, since I no longer need the original file, ‘hashStruct.bin’, I decided it would be better to just delete the file using unlink().

use Storable;

%hash = %{retrieve("hashStruct.bin")};
foreach my $key (keys %hash ) {
    print "$key ->; $hash{$key}\n";
exit 0;

Here is my output from standard out:
secondNibble -> HASH(0x7adf70)
0 -> 0x00
firstNibble -> HASH(0x34cd90)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s