sub execSubroutine { my $sub = shift; my @sub_ret = &{$sub}(@_); # Return an list if we get a list with more than one value # this will satisfy callers expecting lists and/or hashes return @sub_ret if (@sub_ret > 1); my $rval = $sub_ret[0]; # If we have a ref de-reference and return. if (my $type = ref($rval)) { return @$rval if ($type eq 'ARRAY'); return %$rval if ($type eq 'HASH'); } # If not a ref and the caller wants a list, give it to them if (wantarray) { return @sub_ret; } # Otherwise return a scalar return $rval; }
To add staples to the belt and suspenders, and to cover the chance that the sub you are calling displays different behavior in list versus scalar contexts, you could try the following:
This ensures that the calling context is supplied to the target.sub execSubroutine { my $sub = shift; my (@array, $scalar); if (wantarray) { @array = &{$sub}(@_); return @array if (@array != 1); $scalar = $array[0]; } else { $scalar = &{$sub}(@_); } my $rval = $scalar; # If we have a ref de-reference and return. if (my $type = ref($rval)) { return @$rval if ($type eq 'ARRAY'); return %$rval if ($type eq 'HASH'); } # Otherwise return a scalar return $rval; }
In reply to Re: Determining subroutine return type
by herveus
in thread Determining subroutine return type
by satchm0h
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |