CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [zohman] creating reference from within hash?: Edit Log



Laurent_R
Veteran / Moderator

May 25, 2017, 1:35 AM


Views: 2971
Re: [zohman] creating reference from within hash?

Maybe I misunderstand what you're trying to do or I am otherwise confused, but I have the feeling you can't really do what you want, because in:


Code
'TestAppV2' => { id => $hash{'TestApp'}{id}, host => 'host2' }

the "$hash{'TestApp'}{id}" will be evaluated to its content, so that you will effectively end up with the same hash as your original one. I am afraid that this will happen even if you use a reference to "$hash{'TestApp'}{id}".

The closest to what you're trying to do that I could come up with is to store the reference as a sting within single quotes to prevent interpolation:


Code
use strict; 
use warnings;
use Data::Dumper;

my %Hash = ( 'TestApp' => { id => 'APP10', host => 'host1' },
'TestAppV2' => { id => 'APP10', host => 'host2' },
'TestApp2' => { id => 'APP11', host => 'host43' },
'TestApp2V2' => { id => 'APP11', host => 'host49' }
);

print "Before: ", Dumper \%Hash;

my %temp_hash;
for my $key (keys %Hash) {
my $id = $Hash{$key}{id};
if (exists $temp_hash{$id}) {
$Hash{$key}{id} = $temp_hash{$id};
} else {
$temp_hash{$id} = '$Hash{$key}{id}';
}
}

# print Dumper \%temp_hash;
print "\nAfter: ", Dumper \%Hash;


This would display the following:


Code
$ perl nested_hash.pl 
Before: $VAR1 = {
'TestApp2' => {
'id' => 'APP11',
'host' => 'host43'
},
'TestApp2V2' => {
'id' => 'APP11',
'host' => 'host49'
},
'TestAppV2' => {
'id' => 'APP10',
'host' => 'host2'
},
'TestApp' => {
'id' => 'APP10',
'host' => 'host1'
}
};

After: $VAR1 = {
'TestApp2' => {
'id' => 'APP11',
'host' => 'host43'
},
'TestApp2V2' => {
'id' => '$Hash{$key}{id}',
'host' => 'host49'
},
'TestAppV2' => {
'id' => 'APP10',
'host' => 'host2'
},
'TestApp' => {
'id' => '$Hash{$key}{id}',
'host' => 'host1'
}
};



But I doubt that's really what you need, because you won't be able to do much with these strings (well, you can eval them if $key is properly defined at the point where you need it, but that does not seem to buy you very much).

This seems to be a XY problem, i.e. a case where you think you can solve the X problem by using Y, and ask about Y. May be should should tell us about X, that is about the real underlying thing that you want to achieve.

Or, again, perhaps I am confused about your question.


(This post was edited by Laurent_R on May 25, 2017, 1:51 AM)


Edit Log:
Post edited by Laurent_R (Veteran) on May 25, 2017, 1:37 AM
Post edited by Laurent_R (Veteran) on May 25, 2017, 1:51 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives