Search code examples
arraysperlternary

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.


Solution

  • 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.