2

can anyone please explain the importance and how to use bless in perl. I have read many threads on stack overflow on bless but they are not clear.

Rahul Reddy
  • 12,613
  • 10
  • 22
  • 21

3 Answers3

7

This is a way to make Perl treat packages as object oriented classes, and the blessed objects as instances of those classes.

Blessing a reference marks it so that the interpreter knows what package it is associated with. For example, if you write:

$x = {}; bless $x, "somepackage";

Then you can later write:

$x->method(1, 2, 3);

And the interpreter will treat this as:

somepackage::method($x, 1, 2, 3);

Here's a real simple example. Create a class in a file called MyClass.pm:

package MyClass;

sub new {
   my ($class_name) = @_;
   my $new_instance = {};
   bless $new_instance, $class_name;
   return $new_instance;
}

sub set {
   my ($self, $name, $value) = @_;
   $self->{$name} = $value;
}

sub get {
   my ($self, $name) = @_;
   return $self->{$name};
}

Now you can use the class in your code:

import MyClass;

my $instance = MyClass->new; # Same as MyClass::new("MyClass")
$instance->set('age', 30);   # Same as MyClass::set($instance, 'age', 30)
print $instance->get('age'); # Same as MyClass::get($instance, 'age')

The arrow operator, combined with how bless binds a reference to a package name, gives you nice object-oriented syntax.

Charles Engelke
  • 5,569
  • 1
  • 29
  • 26
  • `s/scalar/reference/`. You can only bless references. To link arbitrary data structures to an object, `tie` can be used. – amon Jun 20 '13 at 12:02
  • can we use the blessed object anywhere else in the program? Like i bless it in one subroutine and can i use it later in another subroutine? – Rahul Reddy Jun 20 '13 at 12:02
  • @Rahul Reddy: Yes. `bless` alters the reference, not the variable, so wherever you access the same item (via a reference), it will be associated with the package. It is in fact a very simple and lightweight change to the referenced data, but also a cornerstone of OO in Perl. – Neil Slater Jun 20 '13 at 12:26
  • Actually, you can bless any scalar, so you can bless a string or a number, not just a reference. But by far the most common and useful case is to bless a reference to a hash. – Charles Engelke Jun 20 '13 at 12:46
  • 1
    @Charles Engelke: That is not true: `perl -e '$x = 5; bless $x,"Foo";'` results in `Can't bless non-reference value at -e line 1.` You can however bless references to things that are not hashes. – Neil Slater Jun 20 '13 at 13:28
  • @NeilSlater: You're absolutely right, my statement is wrong. I'm going to leave my comment because your comment adds value. – Charles Engelke Jun 20 '13 at 19:13
2

The very top of the perlobj documentation gives a helpful explanation with examples.

An Object is Simply a Data Structure

Unlike many other languages which support object orientation, Perl does not provide any special syntax for constructing an object. Objects are merely Perl data structures (hashes, arrays, scalars, filehandles, etc.) that have been explicitly associated with a particular class.

That explicit association is created by the built-in bless function, which is typically used within the constructor subroutine of the class.

Here is a simple constructor:

package File;

sub new {
    my $class = shift;

    return bless {}, $class;
}

The name new isn't special. We could name our constructor something else:

package File;

sub load {
    my $class = shift;
    return bless {}, $class;
}

The modern convention for OO modules is to always use new as the name for the constructor, but there is no requirement to do so. Any subroutine that blesses a data structure into a class is a valid constructor in Perl.

In the previous examples, the {} code creates a reference to an empty anonymous hash. The bless function then takes that reference and associates the hash with the class in $class. In the simplest case, the $class variable will end up containing the string "File".

We can also use a variable to store a reference to the data structure that is being blessed as our object:

sub new {
    my $class = shift;

    my $self = {};
    bless $self, $class;

    return $self;
}

Once we’ve blessed the hash referred to by $self we can start calling methods on it.

Greg Bacon
  • 134,834
  • 32
  • 188
  • 245
1

bless is an older way to construct objects in Perl. For new code, I would recommend using Moose, Moo, or Object::Tiny instead.

Those are options are ordered from the largest in size and complexity (Moose) to the simplest with least features (Object::Tiny).

If you see bless in other perl code, it works as the other answers describe.

Mark Stosberg
  • 12,961
  • 6
  • 44
  • 49
  • I’m sorry, but this really is not a reasonable statement. A lot of us work in places where we have to run with what the vendor gives us and little else. Those are not standard. – tchrist Jun 20 '13 at 21:36
  • It is as least as reasonable as your work place rules, it seems. – Mark Stosberg Jun 21 '13 at 10:27