Main Content

When to bless a Perl variable

Archive - Originally posted on "The Horse's Mouth" - 2005-03-15 19:52:55 - Graham Ellis

Perl's bless function, which turns a reference into an instance of an object, it typically called up as the last action in a constructor method. On today's Perl for Larger Projects course, I was challenged as to when else it might be used. Here's an example - when loading a file of information into objects, in a method that's returning a whole list of objects:


sub fileload {
my ($class,$fname) = @_;
open (FH,$fname);
my @result;
while (<FH>) {
my ($thisclass,$breed,$age,$equiv) = split;
my %self;
$self{breed} = $breed;
$self{age} = $age;
$self{equiv} = $equiv;
push @result, bless \%self,$thisclass;
}
return @result;
}


Interesting, this code's also an example of the two parameter use of bless, where an object is being blessed into a class that's not got the same name as the current package.