will england :: perl arrays and hashes

Newsgroups: comp.lang.perl.misc
Subject: Re: Beginner Question
References: <[email protected]>
Followup-To: 

On Wed, 12 Jul 2000 16:31:52 +0100, Duncan Drury 
 wrote:
>Am I right in thinking that $fred{$key} is completely different to $fred?  I
>think it refers to the scalar variable referenced by $key in the hash %fred.
>Argh, but I can't tell if I am right or wrong!
>

In a nutshell, Yes.  :-)

To elaboryte, $fred is a single scalar; $fred = 16.

%fred is a hash, which is an array using keys instead of numbers
for placeholders.  

To compare:


     Hash %fred:                  Array @fred:
-----------------------------------------------------
  key     | value         |       key   |  value
  -------------------     |       -------------------
  make    | ford          |        0    |  ford
  model   | taurus        |        1    |  taurus
  color   | blue          |        2    |  blue
  trans   | auto          |        3    |  auto

Now, we've got a similar set of values stuffed into both an
array and a hash.

To access any one of the data values in the array, we reference
it like this:

    $fred[2]          #This returns the value 'blue'.

Which means this:  Return the scalar value of whatever is stored
                   in the third slot of array @fred.

"Third" slot you ask?  Yes.  Remember, arrays start numbering
at 0, not 1 in perl.  Another benefit of hashes is that you
have the named keys for reference.

Accessing hashes is similar, and gives you the mnemonic key to
work with as well.  Ex:

    $fred{'color'}   #This also returns the value 'blue'.

This means this:  Return the scalar value of whatever is stored
                  in the slot named 'color' in the hash %fred. 

Now, we still have the old $fred from above which still contains
a single value.

Usage:

print "I have a $fred{'color'} $fred[0] $fred{'model'} and \n";
print "I can drive it when I'm $fred years old.\n";

This returns:

I have a blue ford taurus and
I can drive it when I'm 16 years old.

perldoc perlvar will explain all of this as well.  

HTH,

Will


-- 
  "If Al Gore invented the Internet, then I invented spellcheck!"
      Dan Quayle, quoted at the National Press Club, 8/3/1999 
         pgpkey at http://will.mylanders.com/pub_pgp.asc 
  Recovery page: http://will.mylanders.com/    [email protected] 


The usual suspects

[ Main -- Humor -- Art -- Food ]
[ Shooting -- Motorcycle -- Blog ]

Disclaimer: Anything I have to say is mine, dammnit! My employers, clients nor anyone else can take credit (or be blamed) for it.

Author: Will England ([email protected]) Complaints? /dev/null

This page is a Y to K complaint.

Valid HTML 4.0! Valid CSS!

Updated Thursday, March 07 2002 @ 10:27pm