in reply to RE: RE: Hash Nightmare
in thread Hash Nightmare

As I am relatively new to Perl, I have no idea what merlyn was talking about.

Replies are listed 'Best First'.
RE:(4) Hash Nightmare
by swiftone (Curate) on Oct 06, 2000 at 22:04 UTC
    Okay, lets start with the basics then.

    First, your code is bad practice. If you're new to Perl, you're excused, but we'll show you the Right Way (TM) :). The problem is that by having four different hashes, you data is separated. If you want to check the amount of memory left in a particular computer, what do you refer to? One of many psuedo-global variables. The better way to do it is to organize your data into one nested structure, that approaches the way we think of it.

    "All well and good," you say "but how do I do that?"

    References. (This next section assumes you don't know about references. If you do, too bad, I'm writing it anyway :) )
    A good place to learn about references is the perlref man page. I'll give a quick run down here, but it's important to know that I'll gloss over some details, and use some not-technically-correct terminology. References are a scalar value that refers (surprise) to memory address of a perl variable. (Those familiar with C may compare them to "pointers", but aside from a conceptual simularity, the operations you can do are different, so I won't discuss it further). What can you do with this address? Nothing. But you can dereference it, giving you access to the contents of the original variable. And because a reference is a scalar, you can do lots of neat things with it, only some of which I discuss here.

    For example, a hash can store only scalars, one for each key. But if a reference is a scalar, you could store a reference to, say, a list for each key of the hash. Suddenly your hash has (effectively) two layers.

    In the example you posted, my first solution was to create a list of references to your hashes. merlyn took this to an extreme and separated all your data into nested layers. (Which is good, because it means you can access any discrete piece of information)

    You can check out the syntax for creating and dereferencing references in perlref. Ignore all the sections about "soft" references, that's bad practice.

    Oh, and the obligatory newbie advice:

    • Always use strict.
    • Always have -w in your command line, and -T if it's a CGI script.
      Another good place to check is perlman:perldsc, which describes how to do complex data structures (like merlyn's in Perl.