Chapter 3. Functions

In the context of programming, a function is usually a named sequence of statements that performs a computation. In Perl, functions are often also called subroutines, and the two terms can (for now) be considered more or less equivalent. When you define a function, you specify the name and the sequence of statements. Later, when you want to perform a computation, you can “call” the function by name and this will run the sequence of statements contained in the function definition.

Perl comes with many built-in functions that are quite handy. You’ve already seen some of them: for example, say is a built-in function, and we will see many more in the course of this book. And if Perl doesn’t already have a function that does what you want, you can build your own. This teaches you the basics of functions and how to build new ones.

Function Calls

We have already seen examples of function calls:

> say 42;
42

The name of the function is say. The expression following the function name is called the argument of the function. The say function causes the argument to be displayed on the screen. If you need to pass several values to a function, then just separate the arguments with commas:

> say "The answer to the ultimate question is ", 42;
The answer to the ultimate question is 42

Many programming languages require the arguments of a function to be inserted between parentheses. This is not required (and usually not recommended) in Perl 6 for most built-in functions ...

Get Think Perl 6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.