Should I prefer hashes or hashrefs in Perl?

后端 未结 3 1364
南笙
南笙 2021-02-20 16:35

I\'m still learning perl.

For me it feels more \"natural\" to references to hashes rather than directly access them, because it is easier to pass references to a sub, (

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-20 17:29

    For me the main reason to use $hashrefs to %hashes is the ability to give them meaningful names (a related idea would be name the references to an anonymous hash) which can help you separate data structures from program logic and make things easier to read and maintain.

    If you end up with multiple levels of references (refs to refs?!) you start to loose this clean and readable advantage, though. As well, for short programs or modules, or at earlier stages of development where you are retesting things as you go, directly accessing the %hash can make things easier for simple debugging (print statements and the like) and avoiding accidental "action at a distance" issues so you can focus on "iterating" through your design, using references where appropriate.

    In general though I think this is a great question because TIMTOWDI and TIMTOCWDI where C = "correct". Thanks for asking it and thanks for the answers.

提交回复
热议问题