Packing in Perl objects

One solution to both the localized code problem and the problem of storing multiple data values within a single hash key/value pair is to use a Perl object to encapsulate and hide some of the nasty bits.[17]

The following Perl code defines an object of class Megalith. We can then reuse this packaged object module in all of our programs without having to rewrite any of them, if we change the way the module works:

#!/usr/bin/perl -w # # ch02/DBM/Megalith.pm: A perl class encapsulating a megalith package Megalith; use strict; use Carp; ### Creates a new megalith object and initializes the member fields. sub new { my $class = shift; my ( $name, $location, $mapref, $type, $description ) = @_; my $self = {}; bless $self => $class; ### If we only have one argument, assume we have a string ### containing all the field values in $name and unpack it if ( @_ == 1 ) { $self->unpack( $name ); } else { $self->{name} = $name; $self->{location} = $location; $self->{mapref} = $mapref; $self->{type} = $type; $self->{description} = $description; } return $self; } ### Packs the current field values into a colon delimited record ### and returns it sub pack { my ( $self ) = @_; my $record = join( ':', $self->{name}, $self->{location}, $self->{mapref}, $self->{type}, $self->{description} ); ### Simple check that fields don't contain any colons croak "Record field contains ':' delimiter character" if $record =~ tr/:/:/ != 4; return $record; } ### Unpacks the given string into the ...

Get Programming the Perl DBI now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.