Search code examples
arrayslistscalarperl

Perl: Length of an anonymous list


How to get the length of an anonymous list?

perl -E 'say scalar ("a", "b");' # => b

I expected scalar to return the list in a scalar context - its length.

Why it returns the second (last) element?

It works for an array:

perl -E 'my @lst = ("a", "b"); say scalar @lst;' # => 2

Solution

  • One way

    perl -wE'$len = () = qw(a b c); say $len'   #--> 3
    

    The = () = "operator" is a play on context. It forces list context on the "operator" on the right side and assigns the length of the returned list. See this post about list vs scalar assignments and this page for some thoughts on all this.

    If this need be used in a list context then the LHS context can also be forced by scalar, like

    say scalar( () = qw(a b c) );
    

    Or by yet other ways (0+...), but scalar is in this case actually suitable, and clearest.


    In your honest attempt the scalar imposes the scalar context on its operand -- where there's an expression in this case, which is thus evaluated, by the comma operator. Thereby one after another term is discarded, until the last one which is returned.

    You'd get to know about that with warnings on, as it would emit

    Useless use of a constant ("a") in void context at -e line 1

    Warnings can always be enabled in one-liners as well, with -w flag. I recommend that.


    I'd like to also comment on the notion of a "list" in Perl, often misunderstood.

    In programming text a "list" is merely a syntax device, that code can use; a number of scalars, perhaps submitted to a function, or assigned to an array variable, or so. It is often identified by parenthesis but those really only decide precedence and don't "make" anything nor give a "list" any sort of individuality, like a variable has; a list is just a grouping of scalars.

    Internally that's how data is moved around; a "list" is a fleeting bunch of scalars on a stack, returned somewhere and then gone.

    A list is not -- not -- any kind of a data structure or a data type; that would be an array. See for instance a perlfaq4 item and this related page.