Search code examples
arraysperldefault

How do I use a default array if no command line arguments are given?


The below appears to work correctly if no command line arguments are given, but when they are all I get is the number of arguments supplied, not the arguments themselves. It appears @ARGV is being forced scalar by ||. I've also tried using or and // with similar results. What is the correct operator to use here?

say for @ARGV || qw/one two three/;

Solution

  • The || operator imposes the scalar context by the nature of what it does

    Binary "or" returns the logical disjunction of the two surrounding expressions. It's equivalent to || except for the very low precedence.

    (emphasis mine). Thus when its left-hand-side operand is an array it gets the array's length.

    However, if that's 0 then the right hand side is just evaluated

    This means that it short-circuits: the right expression is evaluated only if the left expression is false.

    what is spelled out in C-Style Logical Or in perlop

    Scalar or list context propagates down to the right operand if it is evaluated.

    so you get the list in that case.

    There is no operator that can perform what your statement desires. The closest may be

    say for (@ARGV ? @ARGV : qw(one two));
    

    but there are better and more systemic ways to deal with @ARGV.