Phoenix.pm: yet another strange beast; $#$var as lvalue

Doug Miles doug.miles at bpxinternet.com
Thu Aug 24 12:17:38 CDT 2000


Michael Dearman wrote:
> 
> Hi,
> 
> Ran up on this in the Perl Algorithms book.
> 
> sub insertion_merge {
> 
>         ...
>         my $merge;      # The merged result.
> 
>         $#$merge = @$large + @$small - 1;       # Pre-extend
> 
> and then $merge used as ref to an array?
> 
>         $merge->[ $i ];
> 
> Two questions.
> 1. Could someone share where any documentation on the $#$var construct?
>    I know I've seen a discussion on manually pre-extending an array
>    instead of relying on Perl to auto-magically do this. But don't
>    remember seeing this.

I've never seen it before either, but I'll take a stab at explaining
it.  You can set an array to be a certain length by assigning to the
last index of the array like this:

$#array = 99; # Gives an array of 100 elements (0-99).

See below for the explanation of the construct in question.

> 2. But the real thing that gets me -
>    At what point and how does $merge become a ref to an array?
>    I kinda see what happens. But I'd appreciate it of someone
>    could put this to words ( or lyrics :)
>    $#$merge = @$arr_1 + @$arr_2 -1;

Let's take this apart piece by piece:

The @ in front of $arr_1 and $arr_2 means that they must resolve to
arrays.  This means that $arr_1 and $arr_2 must be references to arrays,
or an error.  @$arr_1 and @$arr_2 are being used in scalar context, so
they evaluate to the number of elements in each array.  So what you get
is the length of one array plus the length of another array minus 1.  I
would have written it like this for clarity:

@{$arr_1} + @{$arr_2} - 1;

The last part should answer your question.  $# indicates the last
element of an array.  In this case, perl uses this context to make
$merge a reference to an array.  I would have written the whole thing
like this:

$#{$merge} = @{$arr_1} + @{$arr_2} - 1;

I don't know if this is any clearer to anyone else, but it helps me
out.  Hopefully I answered your question (and did it without spreading
misinformation :).

-- 
- Doug

Don't anthropomorphize computers. They hate that.



More information about the Phoenix-pm mailing list