LPM: RE: passing array refs

ken.rietz at asbury.edu ken.rietz at asbury.edu
Fri Jan 21 16:23:04 CST 2000

> is there any way to pass an array ref transparently? ie
> foo(@array,$var);
> but by prototyping or something :) @array is actually passed 
> in as a ref?

The mechanism you are using is not passing references.
Trying to do something like

@array = (1, 2, 3);
$var = 4;
foo(@array, $var);

presumably calls a subroutine like

sub foo {
    my @subarray = shift @_;
    my $subvar = shift @_;

which won't work, since Perl flattens out the parameters of
the function call into a single  parameter array. @subarray
in this call would end up as (1), the first element of @array,
and $subvar would end up as 2, the second element.

References are the way to go. It prevents having to copy the
entire input array, so efficiency improves as well.
Here's an example of the syntax:

my @array = (1, 2, 3);
my $var = 4;
foo(\@array, \$var);     # Using refs. Note the two extra \

sub foo {
    my $subarrayref = shift @_;
    my $subvarref = shift @_;

    my @subarray = @{$subarrayref};   # Braces optional
    my $subvar = ${$subvarref};       # Ditto

    print @subarray;               # Prints 123
    print $subvar;                 # Prints 4

Note that references, even to arrays and hashes, are scalars,
requiring the $ prefix notation. You convert from a reference
by putting the appropriate prefix symbol in front, as in

@subarray = @{$subarrayref};

-- Ken

More information about the Lexington-pm mailing list