2006-01-14

Perl object is just a blessed hash

To work on a small testing utility, I have to pick up perl again. Fortunately my memory still served me well until I got into this problem. How to trun a hash into object. After a little reading of my Learning Perl book. I figured out how it works. Once you understand perl object is just a blessed hash, then the solution is clear.

============================
package MyTest;

use strict;

my %hash = (color=>"red", shape=>"round");
my $hashref = \%hash;

sub not_typical_new {
my ($proto, $arg) = @_;
my $class = ref($proto) || $proto;
my $self = $arg;
bless ($self, $class);
return $self;
}

my $obj = mytest->not_typical_new($hashref);
print $obj->{color}, "\n";

3 comments:

Anonymous said...

A package name that is all lowercase is reserved for "pragma": things that affect how Perl compiles programs.

Also, the "ref($proto) || $proto" is now officially discouraged. See my explanation of why at my article at http://www.stonehenge.com/merlyn/UnixReview/col52.html and as a result of that article, the official docs were changed.

Anonymous said...

A package name that is all lowercase is reserved for "pragma": things that affect how Perl compiles programs.

Also, the "ref($proto) || $proto" is now officially discouraged. See my explanation of why at my article at http://www.stonehenge.com/merlyn/UnixReview/col52.html and as a result of that article, the official docs were changed.

Anonymous said...

Thanks for the advice and maybe I have to read your book again.