4

As a newbie to Perl, I just don't understand what kind of philosophy is behind of the following result:

$cnt1 = @arr;           
# this gives the length of the array 'arr'
$cnt2 = @arr[ @indices_arr ];          
# this gives the last element of the @arr[ @indices_arr ];

Is there someone who can explain the difference between the two?

ikegami
  • 367,544
  • 15
  • 269
  • 518
Byungjoon Lee
  • 913
  • 6
  • 18
  • 1
    Both constructs can be useful. Both are documented. If the language lacked one of those two features people would probably ask what the philosophy is behind not implementing one of them. – DavidO Oct 09 '15 at 23:23

1 Answers1

5

From perldoc perldata:

Assignment to a scalar evaluates the right-hand side in scalar context...

And:

If you evaluate an array in scalar context, it returns the length of the array.

And:

Slices in scalar context return the last item of the slice.

@arr is an array; @arr[ @indices_arr ] is an array slice.


As for the philosophy behind this: lists and arrays are different data types in Perl, with different behaviors (don't be thrown by the @ sigil used in slices, slices are lists, not arrays). See Arrays vs. Lists in Perl: What's the Difference? for an in-depth explanation of the differences between the two.

ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
  • 3
    As to why the evaluate to what they do: It's very useful to get the length of an array. We'll give you that in scalar context since the first or last element are already trivial to obtain (`$a[0]` and `$a[-1]` respectively). // It's not useful to get the length of a slice (it's the same as the number of indexes). In fact, a slice in scalar context doesn't make much sense, but that case needs to be handled, so lets make `@a[4]`behaves the same as `$a[4]` – ikegami Oct 10 '15 at 01:15