in reply to Getting a variable name from a reference

I think, this is not possible, because if you put a reference to a hash, the name of the hash is not saved, just it's adress.

Probably, you could save the name of the hash in the hash before referencing it.

Best regards,
perl -le "s==*F=e=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

  • Comment on Re: Getting a variable name from a reference

Replies are listed 'Best First'.
Re: Re: Getting a variable name from a reference
by erikharrison (Deacon) on Mar 05, 2002 at 13:31 UTC

    You're right - it can't be done without saving the name of the name of the variable and some additional jiggery pokery. At least it can't be done with a hard reference like this. The reason it can't be done is because a hard reference is just and address - so the "thingie" that the address points to might have no varable name, such as an anonymous hash:

    $hashref = {'Anonymous' => 'Hash'}; #hash has no varable #name - just reference

    Additionally, a varable might have more than one name, if it has aliases.

    Back in Perl 4 (which I've never used) there were no hard refs, so you had to use variable - name - plus eval tricks to do reference type stuff. This might do what you want it to (warning - untested code):

    #usr/bin/perl -w use strict; my %hash1 = ('A' => 1); my $hashname1 = 'hash1'; my %hash2 = ('B' => 2); my $hashname2 = 'hash2'; eval qq (print qq(Hashname: $$hashname1 Values:); print join ",",sort +keys %{$hasname1})" ); eval qq (print qq(Hashname: $$hashname1 Values:); print join ",",sort +keys %{$hasname1}) );

    But these kinds of eval tricks I'm not used to - and you probably shouldn't use them anyway. Also, you can't print out a memory address here, unless you add in a pair of hard refs.

    Cheers,
    Erik