Tom Tanner Tom Tanner - 1 month ago 4x
Perl Question

Using tradic operator to select a perl subroutine

I have a situation where I want to call one of two subroutines depending on a fairly simple test, but the parameter list is sadly complex. This would seem to read easiest using the ternary operator and works fine in C, but the perl equivalent is evading me.

Code is something like

$res = ($d eq 'something' ? \func1 : \func2)(parameters);

But perl gets very upset by the
sequence and for the life of me I can't work out what to put there


If you want to use function references you have to wrap them inside subroutine invocation syntax:

&{ something that is a code reference } ($args)

So you would have to rewrite that as:

$res = &{ ($d eq 'something' ? \&func1 : \&func2) } (parameters);

The ternary operator doesn't need to be braced either:

$res = &{ $d eq 'something' ? \&func1 : \&func2 } (parameters);