Functions

Contents | Up | Prev | Next

# 3.2. Functions

How many characters are in the perl motto? Perl can tell that right away:

    print length("There's more than one way to do it"), "\n";

`length()` is a built-in function that tells how many characters are in a string. A function is a named sub-routine that accepts several arguments and returns a value that can be further evaluated as part of a greater expression, or used directly.

To help us understand functions further, let's inspect the perl function `substr` (short for "substring"). `substr` retrieves sub-strings of a given string. The first argument to it is a string, the second is the offset from which to take the substring, and the third is the length of the substring to be taken. The third one is optional and if unspecified, returns the substring till the end of the string.

An example will illustrate it best:

    print substr("A long string", 3), "\n";
    print substr("A long string", 1, 4), "\n";
    print substr("A long string", 0, 6), "\n";

The output of this program is:

    ong string
     lon
    A long

( You may notice that the position of the first character is 0. )

The commas are used to separate the arguments to the function and they are mandatory in perl. The parenthesis that enclose them are optional, though. The above program could have been re-written as:

    print ((substr "A long string", 3), "\n");
    print ((substr "A long string", 1, 4), "\n");
    print ((substr "A long string", 0, 6), "\n");

We need an extra set of parenthesis so `print` (which is also a function) would not be confused and consider only the result of the `substr` operation as its argument. If it makes no sense, then it shouldn't; however, remember that a set of parenthesis, that wraps up the argument list of a function, can do you no harm.

## The int() function

Another useful function is int(). This function takes a number and rounds it down to a near integer (= whole number). Here's an example:

    print "The whole part of 5.67 is " . int(5.67) . "\n";

Contents | Up | Prev | Next