Perl

Describe the different ways to receive parameters in a subroutine

Difficulty: unrated

Source: bregman-arie/devops-exercises by Arie Bregman

Answer

  • List assignment: Using the @_ array. It's a list with the elements that are being passed as parameters.
sub power {
    my ($b, $e) = @_;
    return $b ** $e;
}

&power(2, 3);
  • Individual assignment: We should access to every element of the @_ array. It starts from zero.
sub power {
    my $b = $_[0];
    my $e = $_[1];
    return $b ** $e;
}

&power(2, 3);
  • Using shift keyword: It's used to remove the first value of an array and it's returned.
sub power {
    my $b = shift;
    my $3 = shift;
    return $b ** $e;
}

&power(2, 3);

Source

We can also read the best way in the same S.O answer.