Search code examples
perlreferencesubroutine

perl assign reference to subroutine


I use @_ in a subroutine to get a parameter which is assigned as a reference of an array, but the result dose not showing as an array reference.

My code is down below.

my @aar = (9,8,7,6,5);

my $ref = \@aar;

AAR($ref);

sub AAR {
   my $ref = @_;
   print "ref = $ref";
}

This will print 1 , not an array reference , but if I replace @_ with shift , the print result will be a reference.

can anyone explain why I can't get a reference using @_ to me ?


Solution

  • When you assign an array to a scalar, you're getting the size of the array. You pass one argument (a reference to an array) to AAR, that's why you get 1.

    To get the actual parameters, place the local variable in braces:

    sub AAR {
       my ($ref) = @_;
       print "ref = $ref\n";
    }
    

    This prints something like ref = ARRAY(0x5566c89a4710).

    You can then use the reference to access the array elements like this:

    print join(", ", @{$ref});