Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

three questions on an existing perl subroutine

Tags:

perl

I am trying to use the following perl function, but I am not very clear about three points:

sub inittwiddle { 
    my ($m,$n,$aref) = @_; 
    my $i; 
    $$aref[0] = $n+1; 
    for ($i=1; $i != $n-$m+1; $i++) { 
       $$aref[$i] = 0; 
    } 
    while($i != $n+1) { 
       $$aref[$i] = $i+$m-$n; 
       $i++; 
    } 
    $$aref[$n+1] = -2; 
    $$aref[1] = 1 if ( $m == 0 ); 
} 

First, what does my ($m,$n,$aref) = @_; stand for?

Second, how to understand the $$ for sth like $$aref[0] = $n+1;

And this function was invoked as inittwiddle($M,$N,\@p); what does \@p stand for?

like image 454
user785099 Avatar asked Jan 27 '26 12:01

user785099


1 Answers

  1. @_ is the list of arguments passed to the function. By doing my ($m,$n,$aref) = @_; you're assigning $_[0] to $m, $_[1] to $n, and $_[2] to $aref.

  2. $aref is a scalar value holding a reference to an array. To refer to elements within the array you can either access them via $aref->[0] (this is more idiomatic), or by dereferencing the array reference. By adding a @ to the front, you'd refer to the array (i.e. @$aref). However, you want the first element in the array, which is a scalar, so it's obtained by $$aref[0]. Adding brackets (${$aref}[0]) or using the arrow notation ($aref->[0]) clarifies this a little.

  3. \@p is a reference to the array @p. Since your function takes a scalar as the third argument, you have to pass in a scalar. \@p is such. When you pass an array reference into a function like this, it's important to note that any changes to the array (such as doing $$aref[0] = $n+1) are changes to the original array. If you want to avoid this, you would dereference the array into a temporary one, possibly by doing my @tmparr = @$aref; within the function.

like image 116
CanSpice Avatar answered Jan 29 '26 03:01

CanSpice