Passing Lists to Subroutines in Perl


Because the @_ variable is an array in Perl, it can be used to supply lists to a subroutine. However, because of the way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements from @_. If you have to pass a list along with other scalar arguments, then make list as the last argument as shown below −

Example

 Live Demo

#!/usr/bin/perl
# Function definition
sub PrintList {
   my @list = @_;
   print "Given list is @list\n";
}
$a = 10;
@b = (1, 2, 3, 4);
# Function call with list parameter
PrintList($a, @b);

Output

When the above program is executed, it produces the following result −

Given list is 10 1 2 3 4

Updated on: 29-Nov-2019

586 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements