Using Conditional Operators inside push in Perl

Viewed 107

I am new to Perl development and I wanted to check if using conditional operators inside a push statement is allowed. Something like this

push(@myMap, {
    key1 => value1,
    key2 => value2,
    (condition)?{
        key3 => value3,
    }:(),
    key4 => value4
});

Basically I only want to add a value to a Map based on a condition

1 Answers

Yes, but your code is wrong.

push(@myMap, {
    key1 => value1,
    key2 => value2,

    (condition) ? 
      {                   ### these brackets are wrong
        key3 => value3,
      }                   ###
   :(),

    key4 => value4
});

If the condition is true, you are creating a data structure with an uneven number of elements. It will contain a single hash reference as one of the values, so you don't have key/value pairs anymore, and it might complain.

It will try to do what you want, basically turning that hash ref into its string representation, and then using key4 as the value, leaving you with value4 and undef as the last pair.

Fix:

push(@myMap, {
    key1 => value1,
    key2 => value2,
    (condition) ? ( key3 => value3 ) : (),
    key4 => value4
});
Related