next up previous contents
Next: Passing Arrays to Functions Up: Functions Previous: Function Arguments   Contents

Return Values

Perl provides a return statement which can be used to exit a function, and provide a value when a function call is evaluated. In the absence of a return statement, the value of a function call will be the last expression which was evaluated in the body of the function. Like the argument list to a function, the return value is collapsed into a single list; arrays and hashes will lose their meaning, although their elements will appear as scalars in the list which is returned by the function.

Consider a function which will accept a list of values and will return a list of similar length, but scaled by dividing each element by the element in the list with the maximum value. We can simplify matters by creating a local copy of the list and modifying the local copy, which we can then return to the calling environment. Note that the unusual way that arguments are passed to perl functions can be exploited here; our function can either accept a single array of values, or as many individual scalar and/or array arguments as a user would like.

     sub scaled_list{
        my(@list) = @_;
        my($max,val);
     # first find the maximum value 
        foreach $val (@list){
           $max = $val if $val > $max;
        }
     # now do the scaling
        foreach $val (@list){
           $val /= $max;
        }
        return @list;
     }
We could call scaled_list with either an array, or simply a list of the numbers we wish to scale:
@list = (19,32,41,17);
@scaled = scaled_list(@list);
@scaled = scaled_list(19,32,41,17); # identical to previous call


next up previous contents
Next: Passing Arrays to Functions Up: Functions Previous: Function Arguments   Contents
Phil Spector 2002-10-18