Home arrow Perl Programming arrow Arguments and Return Values in Perl

Arguments and Return Values in Perl

In this third part of a six-part article series on subroutines and functions in Perl, you'll learn about passing arguments into functions, and implicitly and explicitly getting return values. This article was excerpted from chapter six of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).

  1. Arguments and Return Values in Perl
  2. Return Values
By: Apress Publishing
Rating: starstarstarstarstar / 0
April 11, 2012

print this article



Passing Arguments into Functions

As well as being set pieces of code to be executed whenever we need them, we can also use our user-defined functions just like Perl’s built-in functions—we can pass arguments (aka parameters) to the subroutine and expect an answer back.

Just like with Perl’s built-ins, we pass parameters by placing them between the parentheses:


What happens to them there? Well, they end up in one of Perl’s special variables, the array@_, and from there we can get at them. We’ll illustrate this with a subroutine that takes a list of values, adds them up, and prints the total. This example,total1.pl, contains a function namedtotal()that loops through the argument list@_and sums the arguments passed in:

#!/usr/bin/perl -w
# total1.pl

use strict;

total(111, 107, 105, 114, 69);
sub total {
my $total = 0;
$total += $_ foreach @_;
print "The total is $total\n";

And to see it in action:

$ perl total1.pl
The total is 506
The total is 5050

This program illustrates that we can pass any list to a subroutine, just like we can toprint(). When we do so, the list ends up in@_, where it’s up to us to do something with it. Here, we go through each element of it and add them up:

$total += $_ foreach @_;

This is a little cryptic, but it’s how you’re likely to see it done if written by an experienced Perl programmer. You could write this a little less tersely as follows:

my @args = @_;
foreach my $element (@args) {
$total = $total + $element;

In the first example,@_would contain(111, 107, 105, 114, 69), and we’d add each value to$totalin turn.

>>> More Perl Programming Articles          >>> More By Apress Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: