1

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
}),
miken32
  • 42,008
  • 16
  • 111
  • 154
Anoop
  • 11
  • 3
  • Please show more context (code and/or output); this is misleading as it stands – zdim Jun 10 '20 at 10:10
  • 2
    Does this answer your question? [What exactly does Perl's "bless" do?](https://stackoverflow.com/questions/392135/what-exactly-does-perls-bless-do) – Georg Mavridis Jun 10 '20 at 10:41
  • bless turns the parameter passed to an object and returns it http://web.engr.uky.edu/~elias/tutorials/perldoc-html/functions/bless.html – Georg Mavridis Jun 10 '20 at 10:43

1 Answers1

5

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 blessed 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 blessed reference can still be dereferenced and its contents accessed in the same way as if it had not been blessed, 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.

Dave Sherohman
  • 45,363
  • 14
  • 64
  • 102