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?
To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.
When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().
The simplest and most obvious way is to define the array with all the required elements, and then conditionally call push . const myArray = ['a', 'b', 'c', 'd']; condition && myArray.
An array object starts with its first element so the address of the first element of an array will have the same value as the address of the array itself although the expressions &a[0] and &a have different types.
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'}
: (),
]
},
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With