Automatically call hash values that are subroutine references

前端 未结 7 2060
孤街浪徒
孤街浪徒 2021-01-06 07:02

I have a hash with a few values that are not scalar data but rather anonymous subroutines that return scalar data. I want to make this completely transparent to the part of

7条回答
  •  囚心锁ツ
    2021-01-06 07:33

    As noted by Oleg, it's possible to do this using various more or less arcane tricks like tie, overloading or magic variables. However, this would be both needlessly complicated and pointlessly obfuscated. As cool as such tricks are, using them in real code would be a mistake at least 99% of the time.

    In practice, the simplest and cleanest solution is probably to write a helper subroutine that takes a scalar and, if it's a code reference, executes it and returns the result:

    sub evaluate {
        my $val = shift;
        return $val->() if ref($val) eq 'CODE';
        return $val;  # otherwise
    }
    

    and use it like this:

    foreach my $key (sort keys %hash) {
        print evaluate($hash{$key}) . "\n";
    }
    

提交回复
热议问题