0

I’m looking at the code of sub make in perl’s Math::Complex, and the first line of code is:

my $self = bless {}, shift;

and I’m trying to figure out what it’s doing. My guess is that this is a comma operator, which evaluates and then discards the first operand (the bless), and then returns the second operator, the shift, which provides the argument passed to the function. But then what exactly is the bless doing?

TLP
  • 64,859
  • 9
  • 88
  • 146
snoopyjc
  • 315
  • 2
  • 8
  • 4
    No, it's not the comma operator, remember that you can call most functions in perl without parentheses. `bless {}, shift` is equivalent to `bless({}, shift)`. Bless takes two arguments. – hobbs Mar 26 '22 at 02:07

1 Answers1

2

bless turns the passed value into an object of the given class.

The code in Math::Complex looks like this:

sub make {
    my $self = bless {}, shift;
    # ...
    return $self;
}

In this example that thing that gets blessed is an empty hash ref {}, which becomes an object with no members. shift gets the next argument from the given array, or from @_ if no array is given, so in this case it gets the next (here first) argument passed to the function.

The whole thing is used in constructors and other functions that create class instances (objects).

Robert
  • 6,055
  • 26
  • 41
  • 54
  • Ok and the critical thing I was missing is that the shift value gets passed to the bless function as the class – snoopyjc Mar 26 '22 at 03:17
  • Thanks again, with your help I was able to automatically translate the perl Math::Complex into Python and have the 1000+ test cases pass!! https://github.com/snoopyjc/pythonizer – snoopyjc Mar 31 '22 at 23:05