Variadic Functions in Perl

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

Here’s a function that will take an arbitrary number of ints as arguments.

use strict;
use warnings;

sub sum {
    my (@nums) = @_;
    print "@nums ", " ";
    my $total = 0;
    foreach my $num (@nums) {
        $total += $num;
    }
    print "$total\n";
}

sum(1, 2);
sum(1, 2, 3);

my @nums = (1, 2, 3, 4);
sum(@nums);

To run the program, save the code in a file, say variadic-functions.pl, and run it using Perl.

$ perl variadic-functions.pl
1 2  3
1 2 3  6
1 2 3 4  10

In Perl, we handle variadic functions using the concept of array parameters. The @nums parameter inside the subroutine captures all the passed arguments as an array. We can then perform operations like iterating over the array to compute the sum.

Another key aspect of functions is their ability to form closures, which we’ll look at next.