1

Let have a code:

use 5.014;
use warnings;

my $def = 'default_value';

# this works,.
# e.g. unless here are some arguments
# assigns to element0 the value $def
my(@arr) = (@ARGV);
push @arr, $def unless @arr;
say "args: @arr";

# this also works
# same for scalar - ARGV[0]
my $a1 = $ARGV[0] // $def;
say "arg1: $a1";

Exists some shorten way to assign default values to the array if here no @ARGV?

#this not works
#my(@arr) = (@ARGV) // ('def');

2 Answers 2

4

Assign value to array unless defined

There's no such thing as a defined or undefined array.

To assign to an array if it's empty,

@arr = 'def' if !@arr;

Exists some shorten way to assign default values to the array if here no @ARGV?

@ARGV always exists.

To copy an array into another, using alternate values if the source array is empty, you can use the following:

my @arr = @ARGV ? @ARGV : 'def';
Sign up to request clarification or add additional context in comments.

Comments

3

The simple

my @arr = @ARGV ? @ARGV : ('def');

where you may omit the parenthesis if there is indeed just one value to assign.

That last example doesn't work because //, ||, and && evaluate the definedness or truth of their left-hand side, so they impose a scalar context on their left-hand side (coerceing the array into a count of its elements). See it in perlop.

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.