Search code examples
perlsubroutine

Declaring variables in Perl functions


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.

1  #!/usr/bin/perl 
2  
3  package Person;
4 
5  sub new
6  {
7     my $class = shift;
8     my $self = {
9         _firstName => shift,
10        _lastName  => shift,
11        _ssn       => shift,
12    };
13    # Print all the values just for clarification.
14    print "First Name is $self->{_firstName}\n";
15    print "Last Name is $self->{_lastName}\n";
16    print "SSN is $self->{_ssn}\n";
17    bless $self, $class;
18    return $self;
19 }
20 sub setFirstName {
21    my ( $self, $firstName ) = @_;
22    $self->{_firstName} = $firstName if defined($firstName);
23    return $self->{_firstName};
24 }
25
26 sub getFirstName {
27    my( $self ) = @_;
28    return $self->{_firstName};
29 }
30 1;

Solution

  • 20 sub setFirstName {
    21    my ( $self, $firstName ) = @_;
    

    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.