in reply to Re: where to look up "funny looking" perl notation (and an example)
in thread where to look up "funny looking" perl notation (and an example)

d'oh. guess that's a clear case of lack of RTFMing

Since we are on the subject, am I right in thinking that the 'last index' will always be one less than scalar @array? Or is there something more to it?

  • Comment on Re: Re: where to look up "funny looking" perl notation (and an example)
  • Download Code

Replies are listed 'Best First'.
Re: Re: Re: where to look up "funny looking" perl notation (and an example)
by Gilimanjaro (Hermit) on Jan 21, 2003 at 20:46 UTC
    Almost always true...

    If it wasn't for the fact that you can change the base-index of perl arrays to something other then 0... But I've never seen anyone use that feature yet. The global parameter for the feature is '$['.

    So use $# to get the last defined element index so you can safely add (or loop), and use scalar @array to find out how many elements there are in the array...

      Read perldoc perldata again!

      Version 5 of Perl changed the semantics of $[: files that don't set the value of $[ no longer need to worry about whether another file changed its value. (In other words, use of $[ is deprecated.) So in general you can assume that
      scalar(@whatever) == $#whatever + 1;

        Very true! But I still felt the history was relevant, as it sort of explains why the $# exists at all... And one could still use it, if one wanted to... (Notice the repetitive usage of the word 'one' in this context ;) )
      For getting the 'last defined index' in an array - if you are using it as a subscript - I prefer $array[-1] = $foo; over $array[$#array] = $foo;

      $#array is still useful if you are looping over an array by index, like this

      for my $i (0..$#array) { # do something with $array[$i] }

      -- Hofmator

Re: Re: Re: where to look up "funny looking" perl notation (and an example)
by Mr. Muskrat (Canon) on Jan 21, 2003 at 20:39 UTC
    You are correct...

    Once again, perldoc perldata to the rescue...

    scalar(@whatever) == $#whatever + 1;