[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Dereferencing etc.



Peta Adams / John Murray wrote:
> 
> foreach $key (keys(%$hashname)) (c) {
                     ^^^^^^^^^^^

Hash dereference.

> print "key:  $key, value: $hashname{$key}","\n"; (d)
                            ^^^^^^^^^^^^^^^

No hash dereference.


${$hashname}{$key}

Hash dereference.


$hashname->{$key}

Hash dereference.


(You can use either of those two expressions in your code.)


> The %$hashname bit works OK.
>
> The $hashname{$key} bit dosen't. My guess is that the expression
> $hashname{$key}
> is settup to look for a hash in a table of hashes with the name 'hashname',
> or the creation of the hash %test creates a scalar $test implicitly at the
> time of it's creation.
> 

$hashname{$key} looks in the hash %hashname, just as you would expect.

%hashname = ('foo', 1);
print $hashname{foo};


> The references bit has me a little confused. VIncent Nonnenmacher wrote:
> "$hashname is a reference to the associative array not the array itself
> try to dereference it using the $$ref or $ref-> syntax".
> 
> I understand the concept. I can't see how you can distinguish the
> occurrence of $hashname in $hashname{$key} from the $hashname in
> (keys(%$hashname)).
> 

The occurence of $hashname in $hashname{$key} is followed by {$key}.  The $
at the beginning means the variable is a scalar.  The {} index means that
the variable is a scalar which is an element of a hash.

The occurence of $hashname in %$hashname is not followed by any indices.
The $ at the beginning means the variable is a scalar.  The lack of indices
means the variable is a plain scalar variable.

In other words, you need to use the prefix character *and* the indices to
determine the meaning of a variable name.

$var, @var, and %var are three separate entities.  $var[0] is an element of
@var, and $var{foo} is a value in %var.  $var[0] and $var{0} have no
connection to $var, nor to each other, beyond the coincidental sharing of
part of their names.


Hope that helps!

Ronald

***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch