subroutines beginner

How to define a subroutine in Perl?

Question

How to define a subroutine in Perl?

Defining a subroutine in Perl is a fundamental skill for organizing and reusing code. Subroutines (often called "subs") are blocks of code you can call by name to perform a specific task, making your programs modular and easier to maintain.

Basic Syntax

In Perl, you define a subroutine using the sub keyword followed by the subroutine name and a code block. The typical syntax looks like this:

sub subroutine_name {
    # code here
}

You then call the subroutine by simply using its name with parentheses (parentheses are optional if no arguments):

subroutine_name();

Passing Arguments and Returning Values

Perl subroutines receive their arguments via the special array @_. Each argument is accessed by its index, e.g. $_[0], $_[1], etc. You can also assign these to named variables for readability.

A subroutine returns the value of the last evaluated expression by default, or you can explicitly use the return keyword.

Example: Defining and Calling a Subroutine

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

# Define a subroutine that greets a person by name
sub greet {
    my ($name) = @_;    # Retrieve first argument from @_
    return "Hello, $name!";
}

# Call the subroutine and print the result
my $message = greet("Alice");
print "$message\n";

This example shows:

  • sub greet { ... } defines the subroutine named greet.
  • my ($name) = @_; extracts the first argument passed to the subroutine.
  • Returning a string with return.
  • Calling greet("Alice") and printing the result.

Perl Concepts Highlighted

  • Sigils: The sigil $ is used for a scalar, so $name holds a string.
  • Context: Subroutines return the last evaluated value in scalar or list context.
  • TMTOWTDI (There's More Than One Way To Do It): You could omit return and rely on the last expression, or handle arguments differently (e.g., shift).

Common Pitfalls

  • Forgetting to use strict and warnings, which help catch bugs like typos in sub names or variable declarations.
  • Not unpacking @_ properly and accidentally modifying the argument array directly.
  • Misunderstanding context and return values—e.g., a subroutine returning a list in scalar context returns the last element.

Summary

To define a subroutine in Perl, use the sub keyword with a name and a code block. Access input arguments through @_, return results explicitly or by the last expression, and call your subroutine with its name. This modular approach keeps your code clean and reusable.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 4ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions