next up previous contents
Next: Example: Creating a Data Up: References Previous: Passing Parameters to Functions

The ref() Function

Using references to pass arrays into a function worked well and it was easy, wasn't it? However, what happens if you pass a scalar reference to the firstSub() function instead of an array reference? Listing 8.1 shows how passing a scalar reference when the function demands an array reference causes problems no_ref.pl.

firstSub( 10, ("A".."E") );



sub firstSub {

    my($ref_firstArray, $ref_secondArray) = @_ ;



    print("The first array is  @{$ref_firstArray}.\n");

    print("The second array is @{$ref_secondArray}.\n");

}

This program displays:

Not an ARRAY reference at 08lst01.pl line 9.

Perl provides the ref() function so that you can check the reference type before dereferencing a reference. The next example shows how to trap the mistake of passing a scalar reference instead of an array reference ( scal_ref.pl).

firstSub( 10, ("A".."E") );



sub firstSub {

    my($ref_firstArray, $ref_secondArray) = @_ ;





    print("The first array is  @{$ref_firstArray}.\n")

        if (ref($ref_firstArray) eq "ARRAY");             # One



    print("The second array is @{$ref_secondArray}.\n"

        if (ref($ref_secondArray) eq "ARRAY");            # Two

}

This program displays:

The second array is 1 2 3 4 5.

Only the second parameter is printed because the first parameter-the scalar reference-failed the test on the line marked "One." The statement modifiers on the lines marked "One" and "Two" ensure that we are dereferencing an array reference. This prevents the error message that appeared earlier. Of course, in your own programs you might want to set an error flag or print a warning.

Some values that the ref() function can return are:

Function Call Return Value
ref( 10 ); undefined
ref( \10); SCALAR
ref( \{1 => ; "Joe"} ); HASH
ref(\&firstSub ); CODE
ref( \\10); REF

Another example of the ref() function in action is ref.pl:

$scalar = 10;

@array  = (1, 2);

%hash   = ( "1" => "Davy Jones" );



# I added extra spaces around the parameter list

# so that the backslashes are easier to see.

printRef( $scalar, @array, %hash );

printRef( \$scalar, \@array, \%hash );

printRef( \&printRef, \\$scalar );



# print the reference type of every parameter.

sub printRef {

    foreach (@_) {

        $refType = ref($_);

        defined($refType) ? print "$refType " : print("Non-reference ");

    }

    print("\n");

}

This program displays:

Non-reference Non-reference Non-reference

SCALAR ARRAY HASH

CODE REF

By using the ref() function you can protect program code that dereferences variables from producing errors when the wrong type of reference is used.


next up previous contents
Next: Example: Creating a Data Up: References Previous: Passing Parameters to Functions
dave@cs.cf.ac.uk