Acessing function parameters in Perl

Perl functions don’t have parameters, their arguments are passed in an array @_. You can simulate parameters by assigning to a list, but you can also just apply the usual array operations to @_.

Perl

1

2

3

4

subwut{

my@args=@_;

...

}

To put in another way, Perl automatically populates the special @_ variable each time you call a function. You can access it in multiple ways:

directly, by simply using @_ or individual elements within it as $_[0], $_[1], and so on
by assigning it to another array, as shown above
by assigning it to a list of scalars (or possibly a hash, or another array, or combinations thereof):

Perl

1

2

3

4

subwut{

my($arg1,$arg2,$arg3,@others)=@_;

...

}

Note that in this form you need to put the array @others at the end, because if you put it in earlier, it’ll slurp up all of the elements of @_. In other words, this won’t work:

Perl

1

2

3

4

subwut{

my($arg1,@others,$arg2)=@_;

...

}

You can also use shift to pull values off of @_:

Perl

1

2

3

4

5

6

subwut{

my$arg1=shift;

my$arg2=shift;

my@others=@_;

...

}

Note that shift will automatically work on @_ if you don’t supply it with an argument.

You can also use named arguments by using a hash or a hash reference. For example, if you called wut() like:

Perl

1

2

3

4

5

6

7

8

9

10

wut($arg1,{option1=>'hello',option2=>'goodbye'});

...you could thendosomething like:

subwut{

my$arg1=shift;

my$opts=shift;

my$option1=$opts->{option1}||"default";

my$option2=$opts->{option2}||"default2";

...

}

This would be a good way to introduce named parameters into your functions, so that you can add parameters later and you don’t have to worry about the order in which they’re passed.