in reply to Re: Count elements in array ref
in thread Count elements in array ref

I don't understand the purpose of the  @Data + 0; statement in your code examples. Could you please explain? (Note that they produce "Useless use of addition (+) in void context at ..." warnings if warnings are enabled.)


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^3: Count elements in array ref
by JohnCub (Beadle) on Mar 29, 2016 at 20:03 UTC
    According to the camel book, that's a way to force an array to a scalar context. Their example is @days + 0;  # implicitly force @days into a scalar context I'm afraid I don't understand it any more than that.

      The thing to realize about the  @Data + 0; statement in your reply above is that it forces the evaluation of  @Data in scalar context (yielding the number of elements) and then throws away the result!

      All of these statements are equivalent:
          my $n = 0 + @Data;
          my $n = scalar @Data;
          my $n = @Data;
      In the first two, the scalar operation and the use of the scalar built-in on the right hand side of the assignment are redundant because the scalar assignment itself supplies all the scalar context that is necessary. (The usage
          my $n = scalar @Data;
      is sometimes advanced as a best practice for reasons of maintainability: supposedly, it makes crystal clear your intention to get the number of elements of the array.)

      Where forcing scalar context through a null scalar operation or the use of scalar can be useful is in a situation in which the overall context is list, such as in the argument list of the print built-in:

      c:\@Work\Perl>perl -wMstrict -le "my @Data = qw(foo bar baz); ;; print 'hoo ', @Data, ' ha'; print 'fee ', 0 + @Data, ' fie'; print 'hic ', scalar @Data, ' hoc'; " hoo foobarbaz ha fee 3 fie hic 3 hoc


      Give a man a fish:  <%-{-{-{-<