On Wed, Feb 14, 2001 at 06:33:00PM -0500, Michael S. Richey wrote:
> Alright this one has had me stumped to long.
> I've been searching through "Programming Perl (3rd ed.)," but
> have had no luck.  It seems like my references are getting
> converted to strings against my wishes. Can someone

Indeed, your references *are* getting converted to strings, but only because
you wished it, inadvertantly.


> tell me where and why this is happening and how to stop/avoid it?
> 
> 
> I'm getting the following error
> -------------------------------
> Can't use string ("SCALAR(0x80cd828)") as a SCALAR ref while "strict
> refs" in use at ./smalltest.pl line 25.
> 
> 
> In the following code
> -------------------------------
> #!/usr/bin/perl
> 
> use strict;
> 
> # values are the same, can't use them as keys
> my $word = "initial";
> my $num = "initial";
> 
> # the references are unique, use them as keys
> my $wordref = \$word;
> my $numref = \$num;
> 
> # create hash
> my %hash = (
>    $wordref =>  "one",
>    $numref =>  "two"
> );

You just created hash keys which are string representations of
references. Probably not what you want.

> 
> # output should look like:
> # keyval = initial
> # keyval = initial


> 
> # get the values agian
> foreach my $key (keys %hash) {
>    print "keyval = ", ${$key}, "\n";
> }

Here, you are trying to treat a string as a reference, but no dice,
You can make the error go away by saying C<no strict 'refs';>,
but the main problem remains.  

Two easy solutions.

1. 
make each hash value a reference to the key, iterate over the values and
do a double dereference:
  ...
  $wordref => \$wordref.

  ...
  for my $key (values %hash){
        print "keyval = ", $$$key, "\n";
  }

btw, I would say that as:
   print(qq[keyval = $$$_\n]) for values %hash; #requires perl 5.005+ 
   
2. 
eliminate one level of indirection
  my %hash =
  (
  \$word => $word,  
  \$num => $num
 );

Don't be fooled by the references as keys, they get turned into strings.
This means you cannot change the values of $word and $num through the hash
keys.


Now that I have said all that, this whole thing smells really funky. In my
not so humble opinion, this is a solution begging to be re-evaluated.
Depending on what you are trying to accomplish, I can see several different,
easier, and possibly, better ways to do this. If you wish, give us some
specifics and we can help further.

-Gyepi

-- 
It is because the body is a machine that education is possible.
Education is the formation of habits, a superinducing of an artificial
organization upon the natural organization of the body. (Thomas H. Huxley)  

Reply via email to