SPUG: derefencing hash reference / parsing config file (con't)

Andrew Sweger andy at n2h2.com
Sat Jan 8 14:46:01 CST 2000


On Jan 8, 2000 @ 12:14pm, Todd Wells wrote:

> $config{models} = "{CCS = { name = CCS; pool = 1; max = 1; }; };" 
> 
>         my $line = $config{models};
>         $line =~ s/=/=>/g;      # replace "=" with "=>"
>         $line =~ s#\;#\,#g;     # change ";" to ","
>         $line .= ";";           # add a ; to the end so it's Perl
>         $models = eval $line;   # create a models hash
> 
>         print "\nmodels\n=======\n";
>         foreach $var (keys %models)
>         {
>                 my $value = $models{$var};
>                 print "$var is $value\n";
>         }
> 
>         print "models is $models\n";
> 
> My output was only:
> 
> models
> =======
> models is HASH(0x15ba60)

You may be reading too much into it. When you,

my $value = $models{$var};

you have just copied the value found in the hash %models in the $var key
slot to the scalar $value. That value was a reference to a hash.

> So, like I said above, I think this is related to Camel p. 256 and
> Cookbook p.148, hard references don't work as hash keys.

That's not entirely true (more later). In your example above, it is not
the case that you used a reference as a key. There's also some confusion
above on the difference between %models and $models. You've assign the
result of the eval to the scalar $models which is the reference to a hash.
Later you loop over the keys of the hash %models. The two are not quite
related. In the foreach loop, use %$models to get the hash referenced by
the scalar $models.

You can use a reference as the key in a hash, but it will lose (up through
Pelr 5.005_6x at least I think) it's magical referenceishness. But the
value (the scalar created from the reference and used as the key) will
still be unique and can be used in interesting ways.

-- 
  Andrew Sweger <andy at n2h2.com>  |  N2H2, Incorporated
  v=206.336.2947 f=206.336.1541  |  900 Fourth Avenue, Suite 3400
     Advanced Technologies       |  Seattle WA 98164-1059
          Development            |  http://www.n2h2.com/




 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    POST TO: spug-list at pm.org        PROBLEMS: owner-spug-list at pm.org
 Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
 SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
        Email to majordomo at pm.org: ACTION spug-list your_address





More information about the spug-list mailing list