Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally instantiate a new Perl array

Initially, my code looked like this:

my @departments = @{$opts->{'d'}} if $opts->{'d'};

I wanted to refactor the in-line if statement according to Perl Best Practices, so now I've got the following code:

my @departments;
if( $opts->{'d'} )
{
    @departments = @{$opts->{'d'} };
}

$opts is just a hash reference that could possibly have an array ref as the value of a key.

I'd like to do something like the following to keep the code on one line:

my @departments = $opts->{'d'} ? @{$opts->{'d'}} : undef;

But obviously that will just put one element into @departments with value undef.

The reason I'm performing this action in this way is because I later want to be able to check

if( @departments )
{
    my $department_string = join( q{,}, @departments );
    $big_string . $department_string;
}

to dynamically add to a string.

like image 239
s_dolan Avatar asked May 08 '26 09:05

s_dolan


2 Answers

Doing this:

my @departments = $opts->{'d'} ? @{$opts->{'d'}} : undef;

is the same as

my @departments = $opts->{'d'} ? @{$opts->{'d'}} : (undef);

which if $opts->{d} is false will assign a single element, undef, to the array @departments. You don't want an array that contains a single element. You want an empty array.

So, what you want to do is assign an empty list to @departments, like so:

my @departments = $opts->{'d'} ? @{$opts->{'d'}} : ();

One other thing: Your title says "conditionally instantiate a new Perl array", and really what we're doing is conditionally filling it. It's instantiated when you say my @departments.

like image 160
Andy Lester Avatar answered May 11 '26 06:05

Andy Lester


This result in @departments being set to an empty array if the condition fails.

my @departments = $opts->{'d'} ? @{$opts->{'d'}} : ();
like image 37
stevieb Avatar answered May 11 '26 06:05

stevieb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!