BudiBadu Logo
Samplebadu

Perl by Example: Subroutines

Perl 5

Creating reusable code blocks with this sample code demonstrating subroutine definition with sub keyword, argument access via @_ array, parameter unpacking with my, return value behavior, and variable argument handling.

Code

#!/usr/bin/perl
use strict;
use warnings;

# Define a subroutine
sub greet {
    my ($name) = @_; # Unpack arguments
    return "Hello, $name!";
}

# Call the subroutine
my $msg = greet("World");
print "$msg\n";

# Subroutine with multiple arguments
sub add {
    my ($a, $b) = @_;
    return $a + $b;
}

print "Sum: " . add(5, 10) . "\n";

# Variable number of arguments
sub sum_all {
    my $total = 0;
    foreach my $num (@_) {
        $total += $num;
    }
    return $total;
}

print "Total: " . sum_all(1, 2, 3, 4) . "\n";

Explanation

Subroutines in Perl are reusable blocks of code defined using the sub keyword followed by a name and code block. All arguments passed to a subroutine are available in the special array @_, which contains the parameter list. Subroutines do not have formal parameter declarations in their signature; instead, parameters are typically unpacked from @_ into lexically scoped variables using my at the subroutine's beginning.

The return keyword explicitly returns a value to the caller, though if omitted, the value of the last evaluated expression is automatically returned. Variables declared with my inside subroutines are lexically scoped, existing only within that block and preventing interference with global variables or other subroutines. Individual arguments can be accessed directly using $_[0], $_[1], etc., though unpacking into named variables improves readability.

Because @_ is a standard array, subroutines naturally support variable numbers of arguments. Iterating over @_ with foreach processes all passed arguments regardless of count. Subroutines can be called before their definition due to Perl's compilation phase, and can be defined anywhere in the program. Prototypes can be added to subroutine definitions to provide compile-time argument checking, though they are less commonly used in modern Perl.

Code Breakdown

6
sub greet defines subroutine, can be called anywhere in program.
7
my ($name) = @_ unpacks first argument from @_ array into lexical variable.
8
return explicitly returns value, last expression returned if omitted.
26
foreach my $num (@_) iterates all arguments for variable-length parameters.