Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to store refference as a key value in a hash as below
#!/usr/bin/perl -w $a=10; $b{\$a}= $a; ($key,$value)=each %b; print "$$key\n";
monks help me out.

Replies are listed 'Best First'.
Re: Problem to store referrence as key value in a hash
by Corion (Patriarch) on Jan 11, 2008 at 10:00 UTC

    See perldata, first paragraph:

    Hashes are unordered collections of scalar values indexed by their associated string key.

    So, you can't use any scalar as a hash key, just a string.

    There is the module Tie::RefHash though, which allows you to use references as hash keys, which seems to be what you're trying to do.

Re: Problem to store referrence as key value in a hash
by perladdict (Chaplain) on Jan 11, 2008 at 10:23 UTC
    In your example $key stores the reference as string,so you can't convert
    string back to reference,it will not returns a hard reference.

    There is one special kind of hash Tie::RefHash in which we can store reference as keys.
    Below is the code i tried,it may help you to store reference as key in a hash.

    use Tie::Refhash; tie %hash 'tie::RefHash'; %hash =( ["one","two"] => "numbers", ["pen","book"]=> "stationery"); while(my($keyref,$value)=each %h)) { print "@$keyref has $value\n"; }
Re: Problem to store referrence as key value in a hash
by poolpi (Hermit) on Jan 11, 2008 at 10:06 UTC
    #!/usr/bin/perl use strict; use warnings; my $a=10; my %b; $b{\$a}= $a; while ( my ($key, $value) = each %b) { print "$key => $b{$key}\n"; }

    Output:
    SCALAR(0x814f5c4) => 10

    HTH,

    PooLpi
      Output:
      SCALAR(0x814f5c4) => 10

      Err, whatever. Now multiply SCALAR(0x814f5c4) by 2 and tell me the result is 20 :)

      • another intruder with the mooring in the heart of the Perl

        No but :
        print pack('h', 0x814f5c4)
        will give you a nice smiling face ☺
        { use charnames ':full'; my $smiling_face = "\N{WHITE SMILING FACE}"; }
        Tested under XP and the latest Cygwin

        PooLpi ;)