Automatically call hash values that are subroutine references

前端 未结 7 2128
孤街浪徒
孤街浪徒 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:19

    No, not without some ancillary code. You are asking for a simple scalar value and a code reference to behave in the same way. The code that would do that is far from simple and also injects complexity between your hash and its use. You might find the following approach simpler and cleaner.

    You can make all values code references, making the hash a dispatch table, for uniform invocation

    my %hash = (
        key1 => sub { return "value1" },
        key2 => sub {
            # carry on some processing ...
            return "value2"; # In the real code, this value can differ
        },
    );
    
    print $hash{$_}->() . "\n" for sort keys %hash;
    

    But of course there is a minimal overhead to this approach.

提交回复
热议问题