Should I prefer hashes or hashrefs in Perl?

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

    If you can use a plain hashes, to describe your data, you use a plain hash. However, when your data structure gets a bit more complex, you will need to use references.

    Imagine a program where I'm storing information about inventory items, and how many I have in stock. A simple hash works quite well:

    $item{XP232} = 324;
    $item{BV348} = 145;
    $item{ZZ310} = 485;
    

    If all you're doing is creating quick programs that can read a file and store simple information for a report, there's no need to use references at all.

    However, when things get more complex, you need references. For example, my program isn't just tracking my stock, I'm tracking all aspects of my inventory. Inventory items also have names, the company that creates them, etc. In this case, I'll want to have my hashes not pointing to a single data point (the number of items I have in stock), but a reference to a hash:

    $item{XP232}->{DESCRIPTION}  = "Blue Widget";
    $item{XP232}->{IN_STOCK}     = 324;
    $item{XP232}->{MANUFACTURER} = "The Great American Widget Company";
    
    $item{BV348}->{DESCRIPTION}   = "A Small Purple Whatzit";
    $item{BV348}->{IN_STOCK}      = 145;
    $item{BV348}->{MANUFACTURER}  = "Acme Whatzit Company";
    

    You can do all sorts of wacky things to do something like this (like have separate hashes for each field or put all fields in a single value separated by colons), but it's simply easier to use references to store these more complex structures.

提交回复
热议问题