100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Subroutines in Perl

Understand how to define and call Perl subroutines, pass arguments via @_, return values, and use references for pass-by-reference semantics.

Control Flow & SubroutinesIntermediate10 min readJul 10, 2026
Analogies

Defining and Calling Subroutines

A subroutine is defined with the sub keyword followed by a name and a block: sub name { ... }. It's called by name, with parentheses around arguments optional but recommended for clarity. Unless you use modern signature syntax, a sub has no formal, named parameter list by default — every argument passed at the call site is flattened into the special array @_.

🏏

Cricket analogy: Calling a specific fielding drill routine at practice, 'run the slip-catching drill', without specifying exact parameters is like calling a Perl sub run_drill();, whatever balls are fed to the drill arrive bundled together, just as arguments arrive bundled in Perl's @_.

Arguments via @_ and Argument Aliasing

@_ doesn't hold copies of the caller's arguments — its elements are aliases to the actual scalar variables passed in. That means an assignment like $_[0] = 0; inside a subroutine mutates the caller's original variable. The standard defensive pattern is to unpack arguments into my variables immediately: my ($a, $b) = @_;, which copies the values before any further code runs.

🏏

Cricket analogy: If a scorer hands the umpire the actual scorebook rather than a photocopy, any correction the umpire scribbles changes the real record, just as Perl's @_ aliases the caller's actual variables, so $_[0] = 0; can silently modify the original.

perl
sub greet {
    my ($name, $greeting) = @_;   # copy out of @_ immediately
    $greeting //= 'Hello';
    return "$greeting, $name!";
}

print greet('Asha'), "\n";
print greet('Ravi', 'Namaste'), "\n";

# wantarray-aware subroutine
sub stats {
    my @nums = @_;
    my $sum = 0;
    $sum += $_ for @nums;
    return wantarray ? (sum => $sum, count => scalar @nums) : $sum;
}

my $total  = stats(1, 2, 3, 4);   # scalar context: 10
my %report = stats(1, 2, 3, 4);   # list context: (sum => 10, count => 4)

Return Values and Context Sensitivity

A subroutine returns explicitly via return EXPR;, or implicitly returns the value of the last expression evaluated if return is omitted. Because Perl propagates calling context into a sub, the built-in wantarray function lets a sub check whether it was invoked in list context, scalar context, or void context, and shape its return value differently for each case.

🏏

Cricket analogy: A commentator's innings summary changes depending on whether it's a short phrase on air or the full ball-by-ball scorecard, just as a Perl sub calls wantarray to return a compact scalar summary or a full list accordingly.

A Perl subroutine without an explicit return statement returns the value of the last expression evaluated, which is often not what you intended, especially when the last statement is a conditional or a for loop, whose own return value can be surprising. Always use an explicit return for anything beyond the simplest one-line sub.

my vs local, and Passing by Reference

my creates a genuinely new, lexically-scoped variable private to its enclosing block. local doesn't create a new variable at all — it temporarily saves and overrides an existing package global's value for the current dynamic scope, automatically restoring the original value when that scope exits. To avoid copying large arrays or hashes into @_, pass a reference instead (\@array, \%hash), which also enables true pass-by-reference semantics.

🏏

Cricket analogy: A player's personal batting stance (my) stays with them wherever they play, but a temporary field restriction set just for one over (local) reverts once that over ends, mirroring how Perl's local overrides a global only within its dynamic scope.

local does not create a new variable the way my does — it temporarily saves and overwrites a package global's existing value for the duration of the enclosing dynamic scope, then restores it automatically. Using local inside a recursive subroutine can produce confusing behavior since every recursive call shares (and temporarily overrides) the same underlying global.

  • Subroutines are defined with sub name { ... } and called by name; parentheses around arguments are optional but recommended for clarity.
  • All arguments are passed to a sub as a single flattened list in the special array @_.
  • @_ elements are aliases to the caller's actual variables — copy them into my variables immediately to avoid accidental mutation.
  • Without an explicit return, a sub returns the value of its last evaluated expression, which can be a subtle bug source.
  • wantarray lets a sub detect whether it was called in list, scalar, or void context and branch its return value accordingly.
  • my creates a private lexical variable; local temporarily overrides a package global's value for the current dynamic scope only.
  • Passing references (\@array, \%hash) avoids copying large data structures and enables true pass-by-reference semantics.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#PerlStudyNotes#SubroutinesInPerl#Subroutines#Perl#Defining#Calling#StudyNotes#SkillVeris#ExamPrep