perl function bless

‮w//:sptth‬ww.theitroad.com

In Perl, the bless function is used to turn a reference into an object by associating it with a package. This allows the reference to be used as an instance of a class with methods and properties defined in the package.

Here's an example that demonstrates the use of the bless function:

use strict;
use warnings;

# define a package for a Person class
package Person;

sub new {
    my $class = shift;
    my $self = {
        name => shift,
        age => shift,
    };
    bless $self, $class;
    return $self;
}

sub get_name {
    my $self = shift;
    return $self->{name};
}

sub get_age {
    my $self = shift;
    return $self->{age};
}

# create a new Person object
my $person = Person->new('John Doe', 30);

# call methods on the object
print $person->get_name(), "\n"; # prints "John Doe"
print $person->get_age(), "\n"; # prints "30"

In the above example, we define a Person class with a constructor (new) and two methods (get_name and get_age). The constructor takes two arguments, the person's name and age, and creates a hash reference containing this information. The bless function is called on this hash reference to associate it with the Person class.

We then create a new Person object using the new method and call the get_name and get_age methods on it to retrieve the person's name and age, respectively.

Note that the bless function can be called on any reference, not just hash references. In general, it is used to associate a reference with a package that defines a class. The package can then define methods and properties that are specific to the class, and these can be called on instances of the class created using the bless function.