in reply to Count elements in array ref

You could try:
my @Data = (); @Data + 0; my $Count = scalar(@Data); print $Count;
Outputs: 0 whereas:
my @Data = ("asdf","345"); @Data + 0; my $Count = scalar(@Data); print $Count;
Outputs: 2

Replies are listed 'Best First'.
Re^2: Count elements in array ref
by AnomalousMonk (Archbishop) on Mar 29, 2016 at 19:29 UTC

    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:  <%-{-{-{-<

      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:  <%-{-{-{-<