next up previous contents
Next: Nesting Function Calls Up: Functions Previous: Scope of Variables

Using a List as a Function Parameter

Now that you understand about the scope of variables, let's take another look at parameters. Because all parameters are passed to a function in one array, what if you need to pass both a scalar and an array to the same function? This next example shows you what happens, func8.pl

firstSub((0..10), "AAAA");



sub firstSub{

    local(@array, $firstVar) = @_ ;



    print("firstSub: array    = @array\n");

    print("firstSub: firstVar = $firstVar\n");

}

This program prints:

firstSub: array    = 0 1 2 3 4 5 6 7 8 9 10 AAAA

Use of uninitialized value at test.pl line 8.

firstSub: firstVar =

When the local variables are initialized, the @array variables grab all of the elements in the @ array, leaving none for the scalar variable. This results in the uninitialized value message displayed in the output. You can fix this by merely reversing the order of parameters. If the scalar value comes first, then the function processes the parameters without a problem, func9.pl

firstSub("AAAA", (0..10));



sub firstSub{

    local($firstVar, @array) = @_ ;



    print("firstSub: array    = @array\n");

    print("firstSub: firstVar = $firstVar\n");

}

This program prints:

firstSub: array    = 0 1 2 3 4 5 6 7 8 9 10

firstSub: firstVar = AAAA

Note You can pass as many scalar values as you want to a function, but only one array. If you try to pass more than one array, the array elements become joined together and passed as one array to the function. Your function won't be able to tell when one array starts and another ends.


next up previous contents
Next: Nesting Function Calls Up: Functions Previous: Scope of Variables
dave@cs.cf.ac.uk