emilford has asked for the wisdom of the Perl Monks concerning the following question:

I'm currently going through the book Effective Perl Programming and came across the following line of code:
$#a = 4; print scalar(@a);
I've never seen this type of syntax before and am a little confused as to what it exactly does. Any input would be appreciated. TIA - Eric

Replies are listed 'Best First'.
Re: I've never seen this before - $#a = 4 - ??
by robobunny (Friar) on Jun 26, 2002 at 18:01 UTC
    $#a is the last index of the array @a. setting it to something lower than what it already is will truncate the array.
    @a = (0..10); print join(" ", @a), "\n"; $#a = 5; print join(" ", @a), "\n";
    0 1 2 3 4 5 6 7 8 9 10
    0 1 2 3 4 5
Re: I've never seen this before - $#a = 4 - ??
by dws (Chancellor) on Jun 26, 2002 at 18:03 UTC
    Assigning to $#a is a seldom-used way of truncating the array @a.   $#a = 4; arranges for the final index of @a to be 4. Hence, @a will hold 5 elements.

    I find that using a slice makes the code more readable.   @a = @a[0..4];

Re: I've never seen this before - $#a = 4 - ??
by mfriedman (Monk) on Jun 26, 2002 at 18:08 UTC
    That can be used to allocate memory for an array before filling it up. It created five elements in @a and sets them all to undef.

    Here's an example:

    perl -MData::Dumper -e '$#foo = 4; print Dumper \@foo'

Re: I've never seen this before - $#a = 4 - ??
by joshua (Pilgrim) on Jun 26, 2002 at 18:03 UTC
    $#a = 4; # Sets the length of the array @a to four print scalar(@a); # Prints how many elements are in the @a array.
    Remeber, arrays start with 0 as the first item.
      Unless of course, someone was a bad boy and played with $[

      Makeshifts last the longest.

Re: I've never seen this before - $#a = 4 - ??
by emilford (Friar) on Jun 26, 2002 at 18:09 UTC
    That was quick. Thanks for the response.