Perl Subroutine Arguments

Subroutines:-

1. Retrieving arguments to a subroutine with shift:

A subroutine's arguments come in via the special @_ array. The shift without an argument defaults to @_.

   sub volume {
       
my $height = shift;
       
my $width = shift;
       
my $depth = shift;

        return $height
* $width * $depth;
   
}


2. Assign arguments to a subroutine with list assignment:

You can also assign arguments en masse with list assignment:

   sub volume {
       
my ($height, $width, $depth) = @_;

        return $height
* $width * $depth;
   
}

3. Handle arguments directly by accessing @_:

In some cases, but we hope very few, you can access arguments directly in the @_ array.

   sub volume {
        return $_
[0] * $_[1] * $_[2];
   
}


references:

This note explains how Perl subroutines receive their arguments. All arguments arrive in the special @_ array, and a bare shift inside a subroutine defaults to shifting from @_, which is the idiomatic way to read them one by one.

Pulling arguments into named variables at the top of a subroutine makes the rest of the code clearer than indexing @_ directly throughout.

Comments

Popular posts from this blog

[Solved] Error: No such keg: /usr/local/Cellar/gcc

[How To] Unfollow Non-followers on Instagram