Should I prefer hashes or hashrefs in Perl?

后端 未结 3 1299
南笙
南笙 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:16

    I think this kind of question is very legitimate: Programming languages such as Perl or C++ have come a long way and accumulated a lot of historical baggage, but people typically learn them from ahistorical, synchronous exposés. Hence they keep wondering why TIMTOWDI and WTF all these choices and what is better and what should be preferred?

    So, before version 5, Perl didn't have references. It only had value types. References are an add-on to Perl 4, enabling lots more stuff to be written. Value types had to be retained, of course, to keep backward compatibility; and also, for simplicity's sake, because frequently you don't need the indirection that references are.

    To answer your question:

    Don't waste time thinking about the speed of Perl hash lists. They're fast. They're memory access. Accessing a database or the filesystem or the net, that is where your program will typically spend time.

    In theory, a dereference operation should take a tiny bit of time, so tiny it shouldn't matter.

    If you're curious, then benchmark. Don't draw too many conclusions from differences you might see. Things could look different on another release.

    So there is no speed reason to favour references over value types or vice versa.

    Is there any other reason? I'd say it's a question of style and taste. Personally, I prefer the syntax without -> accessors.

提交回复
热议问题