Perl Subroutine — How To Use Functions in Perl

Let’s start by creating a simple subroutine in Perl. The following subroutine takes no parameters and has no return value; all it does it print “hello”.

use strict;
use warnings;

# Create a greet() subroutine.
sub greet {
	print "hello\n";
}

# Call greet()
greet();
hello

Passing Parameters Into Subroutines in Perl

Often we want to pass one or more parameters (or ‘arguments’) into a subroutine. The way this works in Perl is a little unusual. The arguments appear inside the subroutine in a special array variable, @_.

It’s good practice to explicitly set particular variables to the elements of @_ right at the start of your subroutine.

use strict;
use warnings;

# Greet someone and ask a question.
sub greet {
	my ($person, $object, $greeting) = @_;
	
	# We'll make the first letter of the greeting 
	# upper-case.
	substr($greeting, 0, 1) = uc(substr($greeting, 0, 1));
	
	# Display the greeting.
	print "$greeting $person! Would you like a $object?\n";
}

# Call greet()
greet('Jim', 'drink', 'hello');
Hello Jim! Would you like a drink?

Many programmers like to use shift() instead to get the subroutine arguments inside the subroutine. shift() removes items from the start of an array, one at a time; if no array is supplied, it uses the @_ array by default.

The following program is exactly equivalent to the one above.

use strict;
use warnings;

# Greet someone and ask a question.
sub greet {
	my $person = shift;
	my $object = shift;
	my $greeting = shift;

	# We'll make the first letter of the greeting 
	# upper-case.
	substr($greeting, 0, 1) = uc(substr($greeting, 0, 1));
	
	# Display the greeting.
	print "$greeting $person! Would you like a $object?\n";
}

# Call greet()
greet('Jim', 'drink', 'hello');

We can write this program in yet another way; since hashes can be cast to arrays and vice-versa in Perl, we can pass arguments to subroutines as anonymous hashes. This is very useful for passing many arguments to a subroutine, especially where some of the arguments are optional.

use strict;
use warnings;

# Greet someone and ask a question.
sub greet {
	my %args = @_;
	
	my $person = $args{'person'};
	my $object = $args{'object'};
	my $greeting = $args{'greeting'};
	
	# We'll make the first letter of the greeting 
	# upper-case.
	substr($greeting, 0, 1) = uc(substr($greeting, 0, 1));
	
	# Display the greeting.
	print "$greeting $person! Would you like a $object?\n";

}

# Call greet()
greet('person' => 'Jim', 
    'object' => 'drink', 
    'greeting' => 'hello');

Learn Perl By Doing It

box3d_160x120

Get the complete course here

Includes 11 completely free videos – no subscription necessary.

Passing Complex Data Structures to Subroutines in Perl

You can easily pass complex data structures to subroutines by using references.

use strict;
use warnings;

sub greet {
	my ($people, $greetings) = @_;
	
	foreach my $person(@$people) {
		my $greeting = $greetings->{$person};
		
		print "$greeting $person\n";
	}
}

my @people = ('Jim', "Lisa", "Bob");

my %greetings = (
	'Jim' => 'Hello',
	'Lisa' => 'Hi',
	'Bob' => 'Get lost',
);

greet(\@people, \%greetings);

Hello Jim
Hi Lisa
Get lost Bob

Returning Values From Subroutines in Perl

Returning scalar (single) values from subroutines in Perl is very easy, and works just the same as in other languages.

use strict;
use warnings;

sub greet {
	
	my $greeting = "Hello there";
	
	return $greeting;
}

# Print the return value of greet()
# Could also do 
# my $string = greet();
print greet();
Hello there

You can also return arrays:

use strict;
use warnings;

sub greet {
	
	my @greeting = ('hello', 'there');
	
	return @greeting;
}

my @strings = greet();

print join(' ', @strings);
hello there

And you can return hashes:

use strict;
use warnings;

sub greet {
	
	my %greeting = (
		1 => 'hello',
		2 => 'there',
	);
	
	return %greeting;
}

my %greeting = greet();

print $greeting{1} . ' ' . $greeting{2} . "\n";
hello there

But it’s often useful to return complex data structures as references.

use strict;
use warnings;

sub greet {
	
	my %greeting = (
		1 => 'hello',
		2 => 'there',
	);
	
	return \%greeting;
}

my $greeting = greet();

print $greeting->{1} . ' ' . $greeting->{2} . "\n";

You can even very easily return an array of references to complex data structures using this technique.

For example:

use strict;
use warnings;

sub greet {
	
	my %greeting = (
		1 => 'hello',
		2 => 'there',
	);
	
	my @an_other = ('some', 'array');
	
	return (\%greeting, \@an_other);
}

my ($greeting, $an_other) = greet();

print $greeting->{1} . ' ' . $greeting->{2} . "\n";
print $an_other->[0] . ' ' . $an_other->[1] . "\n";
hello there
some array

Default Return Value

While it’s good practice to explicitly return a value in a Perl subroutine (unless there is no return value), Perl actually returns the last defined value from your subroutine by default.

As we’ve seen, shift() uses the @_ variable by default. This means we can write hideous things like the following in Perl. But please don’t; while the following code is legal and works, it is unnecessarily cryptic.

use strict;
use warnings;

sub greet {
	shift() . shift();
}

print greet('cat', 'fish');
catfish

All pages on this site are copyright © 2013 John W. Purcell

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Posted in Perl | Tagged , , |