What does this bless means in below hash value, and how to dereference it?
'limit' => bless( {
'days' => 2,
'minutes' => 0,
'months' => 0,
'nanoseconds' => 0,
'seconds' => 0
}),
What does this bless means in below hash value, and how to dereference it?
'limit' => bless( {
'days' => 2,
'minutes' => 0,
'months' => 0,
'nanoseconds' => 0,
'seconds' => 0
}),
bless
is a core piece of Perl's mechanism for object-oriented programming, as documented in perldoc bless
and perldoc perlobj
.
The statement in the question exists inside of a package; look above it in the source file for a line saying package SomeName
to find out what package it is a part of. If there is no package
statement, then it's a part of package main
by default, but that should basically never be the case if bless
is being used.
In core Perl, a package and an OO class are more-or-less synonymous, while objects are just references which are declared to be a member of that class/package. bless
is the command used to make that declaration.
(There are a number of more full-featured OO frameworks for Perl, such as Moo and Moose, which add features beyond those provided by the basic bless
ed reference model, but you generally don't use bless
yourself when using such a framework, so I'm assuming that no such framework is being used in the code you're looking at.)
For a more concrete example:
package MyClass;
sub show_foo { my $self = shift; return $self->{foo} }
my $var = { foo => 'bar' }; # $var is a normal hash reference
bless $var; # $var is now an object of type MyClass
A bless
ed reference can still be dereferenced and its contents accessed in the same way as if it had not been bless
ed, but it is generally preferable to use the methods defined by the class instead of going directly into the guts. e.g., With the example code above, it would be better to get the value of $var
's foo
property by using $var->show_foo
than with $var->{foo}
, although both ways will work.