- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

19.3 Another Example: Key is a C int.

Here is another real-life example. By default, whenever Perl writes to a DBM database it always writes the key and value as strings. So when you use this:

$hash{12345} = "something";

the key 12345 will get stored in the DBM database as the 5 byte string "12345". If you actually want the key to be stored in the DBM database as a C int, you will have to use pack when writing, and unpack when reading.

Here is a DBM Filter that does it:

use strict;
use warnings;
use DB_File;
my %hash;
my $filename = "filt";
unlink $filename;
my $db = tie %hash, 'DB_File', $filename, 
    O_CREAT|O_RDWR, 0666, $DB_HASH 
  or die "Cannot open $filename: $!\n";
$db->filter_fetch_key  ( sub { $_ = unpack("i", $_) } );
$db->filter_store_key  ( sub { $_ = pack ("i", $_) } );
$hash{123} = "def";
# ...
undef $db;
untie %hash;

The code above uses DB_File, but again it will work with any of the DBM modules.

This time only two filters have been used; we only need to manipulate the contents of the key, so it wasn't necessary to install any value filters.

ISBN 9781906966027Perl Language Reference ManualSee the print edition