Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/;
like image 417
Pascal Avatar asked Sep 10 '17 04:09

Pascal


People also ask

How do you check if there are no command line arguments?

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.

What is the value of args in main method if we don't pass any command line argument?

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.

How do you check if there are command line arguments in Java?

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.

What is argv 0 in command line arguments?

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.


1 Answers

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.

like image 107
zdim Avatar answered Nov 15 '22 17:11

zdim