Perl Subroutines (functions)

Perl Subroutines (functions)

Subroutines, often called functions in other languages, are a way to group code into logical chunks that can be reused. In Perl, a subroutine is defined with the sub keyword, and it can be called using its name.

Defining a Subroutine

Here's a simple example of a subroutine that prints "Hello, world!":

sub say_hello { print "Hello, world!\n"; } 

Calling a Subroutine

You can call this subroutine like this:

say_hello(); # Prints "Hello, world!" 

Note that the parentheses are optional if you're not passing any arguments. This would also work:

say_hello; # Prints "Hello, world!" 

Passing Arguments to a Subroutine

You can pass arguments to a subroutine. Inside the subroutine, these arguments are available in the @_ array:

sub greet { my $name = $_[0]; # The first argument print "Hello, $name!\n"; } greet("Alice"); # Prints "Hello, Alice!" 

It's common to immediately shift the arguments off of @_ and into named variables for clarity:

sub greet { my ($name) = @_; # Same as above print "Hello, $name!\n"; } 

Returning Values from a Subroutine

A subroutine automatically returns the value of the last expression in its body. You can also use the return keyword to return a value early:

sub add { my ($x, $y) = @_; return $x + $y; } my $sum = add(1, 2); # $sum is now 3 

Private Variables in a Subroutine

The my keyword creates a lexically scoped variable, which is private to the subroutine:

sub add { my ($x, $y) = @_; my $sum = $x + $y; return $sum; } 

In this case, $sum is only accessible within the add subroutine.

State Variables

Starting from Perl 5.10, you can use the state keyword to create a variable that retains its value between calls to the subroutine:

use 5.010; sub counter { state $count = 0; return ++$count; } print counter(); # Prints "1" print counter(); # Prints "2" 

In this case, $count retains its value between calls to counter, so it acts like a persistent counter.


More Tags

recordset go-templates endpoint android-multidex xcode11 grails-orm subscription android-toolbar image-scaling v8

More Programming Guides

Other Guides

More Programming Examples