Mike Gossland’s Perl Tutorial Course for Windows

Chapter 3. Functions

Introduction to Functions > String Functions >
Array Functions > Test Functions > User Functions

Introduction to Functions

This chapter introduces functions in Perl. I will introduce the more commonly used built-in functions and then show you how to add to these by creating your own user functions.

Functions are small blocks of code that can be run simply by using the function's name in the script. Quite often functions will have inputs, specified as a list passed to the function in parentheses. The function nearly always has a value which can be returned and assigned to a variable.

As an example of a function consider a made-up "add" function:

$sum = add(1, 2);

The function is being given the values 1 and 2 as inputs, and the variable $sum would get the value of 3. This function returns only one value, the sum.

In general however, functions can return more than one value. They can return a list of values, and in such cases the returned list would be assigned to an array:

@names = students( "Perl Course 130" );

This "students" function would return a list of students' names registered for a Perl course, and this list would then be assigned to the array, @names.  The @names array would be created with just enough elements to contain the complete returned list.

This multi-valued return value is a point worth pondering. It means that some Perl functions will return scalars and others will return arrays. Even more interesting, the same function can sometimes return a scalar, and sometimes an array.

When scalars are used, functions are said to be in a "scalar context". When arrays or lists are used, functions are said to be in a "list context". Which of the two contexts are used has a dramatic impact on the meaning of the statement and on the values returned by the functions. You'll see how to determine which context will be used in the next sections.

Next Page

Search this site or the web:

Google
just this site the whole web

Questions? Feedback?

Email me your comments!