In this tutorial, there is code for a Person class. Are you able to explain to me the purpose of line 21/27? I understand concepts like $_ and @_, and I know my is used for declaring local references, but I don't understand those lines in this code context.

If you're interested in doing OO Perl, I would strongly recommend taking a look at Moose which makes a lot of that repetitive boilerplate go away. There is an excellent introduction to Moose in the (free) book Modern Perl
–
friedoNov 23 '11 at 2:34

perlootut is the modern Perl OO tutorial in the official documentation.
–
daximNov 23 '11 at 11:17

3 Answers
3

At the most basic level, this line takes the first two arguments to the subroutine and assigns them to the local variables $self and $firstName.

$person->setFirstName('jeeves');

In the context of object-oriented Perl, the first parameter passed to the method (because this is what the subroutine has become) is a reference to the instance on which the method is invoked ($person is the above example). You need that reference to get to other methods and instance state. It is customary to call it $self. In other languages, there would be something like this built into the language, so that you do not have to extract it manually.

After that first special parameter are the other ("normal") arguments to the method.

Since you understand the concept of @_ you would realise that you could just access these using shift or $_[0] as you need them. The reason for having these lines is more of a best practice. Since Perl doesn't have formal parameters, we normally assign them to named variables at the beginning of the subroutine before doing anything else. In this way, the code clearly shows what the subroutine expects and what each parameter is. (A reason why you might choose not to do this is for code efficiency, but normally you should choose code clarity first.)

Note the parentheses around the variables. This is to assign the @_ array to the list containing ($self, $firstname). If you don't have the parentheses, it won't work because it is trying to assign an array to multiple scalars. Note that if @_ contains more parameters, they will be ignored.

The list is declared using my. This means that those scalars will exist only within this subroutine. This is for safety so that, if you use a scalar with the same name somewhere else, you won't get a conflict with unexpected results. Note that you need to have a line with use strict at the top of your file for my to be enforced.

$self is used for object-oriented Perl. It will always the first parameter to a method. So in a call like $obj->firstname($foo), $obj will be assigned to $self inside your method, and $foo will be assigned to $firstname.