What does blessing a variable in Perl mean?
Archive - Originally posted on "The Horse's Mouth" - 2010-09-24 08:25:23 - Graham EllisWhen you "bless" a variable in Perl, what are you doing?
You are taking the address of the variable, and returning a "reference to an object" - that's a result which contains three pieces of information:
1. The address in memory at which the object is held
2. The type of Perl structure that's held there (SCALAR, HASH or ARRAY)
3. The package (class) in which the data that's there resides
Those three pieces of information are the vital elements which let you pass around the single reference to a whole series of other pieces of code, and let those other pieces of code (using just the single reference) make use of and alter that data. The presence of the package information allows for "polymorphism" - that's where the call to a function is diverted to different bits of code depending on the sort of data that's help at the given location.

{ package bus;
sub new {
print "Hiring a bus\n";
my ($class,$passengers) = @_;
bless $passengers,$class;
}
sub getstaff {
my $which = $_[0];
my $ts = int(($$which+40)/41);
return $ts;
}
}

Then we can set up some passenger flows and decide whether to use a bus or train for them:
$swindon = new train(230);
$trowbridge = new bus(200);
print "$swindon ... $trowbridge\n";
I've printed out the blessed variables there - usually something you would NOT do as it would really worry the user to see the strange output, but in this training note it shows you what bless has placed into the variables:
train=SCALAR(0x10082b190)
bus=SCALAR(0x10082aea8)
And we can now work out the number of staff needed for each of them in our program:
foreach $trans($swindon,$trowbridge) {
$sn = $trans->getstaff();
print "Staff needed - $sn\n";
}
Results:
Staff needed - 2
Staff needed - 5
Complete source discussed / used above - [here].