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/;
When there are no arguments on the command-line, the argument array will be empty. So, you check for its length args. length==0 . Save this answer.
main always receives its parameter, which is an array of String . If you don't pass any command-line arguments, args is empty, but it's still there.
We can check these arguments using args. length method. JVM stores the first command-line argument at args[0], the second at args[1], the third at args[2], and so on.
By convention, argv[0] is the command with which the program is invoked. argv[1] is the first command-line argument. The last argument from the command line is argv[argc - 1] , and argv[argc] is always NULL.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With