next up previous contents
Next: Scope of Variables Up: Functions Previous: Using the Parameter Array

Passing Parameters by Reference

Using scalar variables inside your functions is a good idea for another reason-besides simple readability concerns. When you change the value of the elements of the @ array, you also change the value of the parameters in the rest of the program. This is because Perl parameters are called by reference. When parameters are called by reference, changing their value in the function also changes their value in the main program.

For example, func4.pl|:

@array = (0..5);

print("Before function call, array = @array\n");

firstSub(@array);

print("After function call, array =  @array\n");



sub firstSub{

    $_[0] = "A";

    $_[1] = "B";

}

This program prints:

Before function call, array =  0 1 2 3 4 5

After function call, array =   A B 2 3 4 5

You can see that the function was able to affect the @array variable in the main program. Generally, this is considered bad programming practice because it does not isolate what the function does from the rest of the program. If you change the function so that scalars are used inside the function, this problem goes away.

So we now write, func5.pl:

@array = (0..5);

print("Before function call, array = @array\n");

firstSub(@array);

print("After function call, array =  @array\n");



sub firstSub{

    ($firstVar, $secondVar) = @_ ;



    $firstVar = "A";

    $secondVar = "B";

}

This program prints:

Before function call, array =  0 1 2 3 4 5

After function call, array =   0 1 2 3 4 5

This example shows that the original @array variable is left untouched. However, another problem has quietly arisen. Let's change the program a little so the values of $firstVar are printed before and after the function call.

The nex example show how changing a variable in the function affects the main program, func6.pl:

$firstVar = 10;

@array    = (0..5);



print("Before function call\n");

print("\tfirstVar = $firstVar\n");

print("\tarray    = @array\n");



firstSub(@array);



print("After function call\n");

print("\tfirstVar = $firstVar\n");

print("\tarray    = @array\n");



sub firstSub{

    ($firstVar, $secondVar) = @_ ;



    $firstVar = "A";

    $secondVar = "B";

}

And we now get:

Before function call

        firstVar = 10

        array    = 0 1 2 3 4 5



After function call

        firstVar = A

        array    = 0 1 2 3 4 5

By using the $firstVar variable in the function you also change its value in the main program. By default, all Perl variables are accessible everywhere inside a program. This ability to globally access variables can be a good thing at times. It does help when trying to isolate a function from the rest of your program. The next section shows you how to create variables that can only be used inside functions.


next up previous contents
Next: Scope of Variables Up: Functions Previous: Using the Parameter Array
dave@cs.cf.ac.uk