Main Content

What does blessing a variable in Perl mean?

Archive - Originally posted on "The Horse's Mouth" - 2010-09-24 08:25:23 - Graham Ellis

When 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.

Here's a piece of code that defines a bus journey - blessing a scalar variable into the package (it happens to contain the number of passengers who want to travel on the journey) and a methos that's unique to buses telling us that we require one driver per 41 passengers (full bus load) or part thereof:

{ 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;
  }
}



We have a very similar piece of code for a train, except that we'll always need a driver and a guard (2 staff) irrespective of the number of passengers - we just need to add a few carriages if the train's getting a bit full [historic example - railways are currently short of carriages!].

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].