When you call a subroutine in Perl any arguments you supply will be available to the subroutine in a special array called @_
.
The shift
function takes an array as an argument, removes the first element from the array and returns that value.
However, if you call shift
without passing it an array, it operates on the @_
array.
So for example if you call a subroutine like this:
my_sub('one', 'two', 'three');
And the definition of my_sub
starts like this:
sub my_sub {
my $arg1 = shift;
Then the $arg1
variable will contain the string 'one'
and the @_
array will be left with ('two', 'three')
.
The code you're trying to understand seems to relate to object oriented coding. If you call a method on an object like this:
$obj->my_method('one');
Then the my_method
subroutine will actually be passed two arguments in @_
. The first is the object that the method was invoked on (sometimes called the invocant
) which in this example is $obj
. The second argument will be the string 'one'
.
It is very common in object-oriented code to start a method definition like this:
sub my_method {
my $self = shift;
Which means $self
will now contain the invocant and @_
will be left with all the remaining arguments.
In your specific example, you were looking at a constructor which is a special kind of method. Usually it would be called like this:
my $my_obj = MyClass->new($arg1, $arg2);
In which case the invocant will be the name of the class that the new
method was invoked on - the string 'MyClass'
in this example.
It would also be possible to invoke the constructor function on an existing object like this:
my $new_obj = $my_obj->new($arg1, $arg2);
Exactly what the result of this call should be is not at all clear to the casual reader. Should it be a completely new object that is a clone of $my_obj
or should it be a new object that has nothing in common with $my_obj
at all? In the first case, defining a clone
method would be clearer and in the second case, calling the constructor on the class would be clearer.
Your example code is trying to handle these two cases. If the invocant is a class then ref($self)
will return undef
since a plain string (the class name) is not a reference. If the invocant is an object, then ref($self)
will return the name of the class that the object is an instance of.
If you're trying to grok Perl's native support for OO programming then start with the standard tutorial doc. If you just want to do OO programming with Perl then start with Moose.