Is there any way to use a “constant” as hash key in Perl?

前端 未结 9 1757
Happy的楠姐
Happy的楠姐 2021-02-03 20:39

Is there any way to use a constant as a hash key?

For example:

use constant X => 1;

my %x = (X => \'X\');

The above code will cr

9条回答
  •  醉话见心
    2021-02-03 21:14

    Most of the other folks have answered your question well. Taken together, these create a very full explanation of the problem and recommended workarounds. The issue is that the Perl pragma "use constant" really creates a subroutine in your current package whose name is the the first argument of the pragma and whose value is the last.

    In Perl, once a subroutine is declared, it may be called without parens.

    Understanding that "constants" are simply subroutines, you can see why they are not interpolated in strings and why the "fat comma" operator "=>" which quotes the left-hand argument thinks you've handed it a string (try other built-in functions like time() and keys() sometime with the fat comma for extra fun).

    Luckily, you may invoke the constant using explicit punctuation like parens or the ampersand sigil.

    However, I've got a question for you: why are you using constants for hash keys at all?

    I can think of a few scenarios that might lead you in this direction:

    1. You want control over which keys can be in the hash.

    2. You want to abstract the name of the keys in case these change later

    In the case of number 1, constants probably won't save your hash. Instead, consider creating an Class that has public setters and getters that populate a hash visible only to the object. This is a very un-Perl like solution, but very easily to do.

    In the case of number 2, I'd still advocate strongly for a Class. If access to the hash is regulated through a well-defined interface, only the implementer of the class is responsible for getting the hash key names right. In which case, I wouldn't suggest using constants at all.

    Hope this helps and thanks for your time.

提交回复
热议问题