8

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/;
2
  • There is no single operator to use in place of || that would make that work as desired. The closest I can think of is (@ARGV ? @ARGV : qw(one two)) Commented Sep 10, 2017 at 5:06
  • Related question Commented Sep 10, 2017 at 7:56

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@ARGV = @ARGV || qw( one two three );
@Zaid perl -wE'@ary = qw(one two); say for (@ary = @ary || 1..3)' prints 2 3
Oh, I forgot to add the usage line: say for @ARGV;
@Zaid Meets a similar fate, per Сухой27 link. But this is fun: perl -wE'@ary = qw(a b); @ary = @ary || 1..3; say for @ary' prints 2 3 while perl -wE'@ary = qw(a b); @ary = @ary || qw(1 2 3); say for @ary' prints 2.
0

Just write it as two lines.

@ARGV = qw[...] unless @ARGV;
say for @ARGV;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.