Search code examples
arraysperlif-statementperl-data-structures

Adding value to array if condition is fulfilled


I am building an array of hashes of arrays

my @array = (
    {label => 'first hash'},
    {label => 'second hash',
     innerarray => [
        {label => 'first inner hash'},
        {label => 'second inner hash'},
      ]
    },
);

Is there a way to only add the second inner hash only if a condition is fullfilled? Something like this:

my @array = (
    {label => 'first hash'},
    {label => 'second hash',
     innerarray => [
        {label => 'first inner hash'},
        {label => 'second inner hash'} if 1==1,
      ]
    },
);

I tried to rewrite my code using push:

my @innerarray = ();
push @innerarray, {label => 'first inner hash'};
push @innerarray, {label => 'second inner hash'} if 1==1;

my @array = (
    {label => 'first hash'},
    {label => 'second hash',
     innerarray => \@innerarray
    },
);

But it becomes very illegible, as I have to predefine all inner array before using them, which in some cases is several 100 lines of code above the usage.

Is there any way to add the if-condition directly where I insert the array-element?


Solution

  • Use the conditional operator, it is usable as expression.

    my @array = (
        {label => 'first hash'},
        {
            label      => 'second hash',
            innerarray => [
                {label => 'first inner hash'},
                (1 == 1)
                    ? {label => 'second inner hash'}
                    : (),
            ]
        },
    );