The real win in using pseudohashes is when creating and
using objects. As an example, if I create an object based
on a hash:
package hashobject;
sub new {
my ($class) = @_;
$class = ref($class) || $class;
my $self = {};
$self->{variable} = 'foo';
return(bless($self, $class));
}
and then use the resulting object, I can still
autovivify member variables, leading to a whole
raft of typo problems:
my $obj = new hashobject;
$obj->{variablee} = 'bar'; # TYPO...
print $obj->{variable}; # Prints 'foo'
If we move to a pseudohash, the object looks like this:
package pseudohashobject;
use fields qw(variable);
sub new {
my ($class) = @_;
$class = ref($class) || $class;
my $self = bless([\%FIELDS], $class]);
$self->{variable} = 'foo';
return($self);
}
And then (mis)use the object in the same way:
my $obj = new pseudohashobject;
$obj->{variablee} = 'bar'; # TYPO
print $obj->{variable};
the typo actually causes a runtime exception! This
makes very hard to find bugs easy to find, and hence
is a good thing (tm). I would suggest looking into
Damien Conway's Object Oriented Perl (Manning) for
more information. I would almost rate this book as
more important than the Camel!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.