Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Referencing/DeReferencing problem

Status
Not open for further replies.

Tve

Programmer
May 22, 2000
166
FR

Hi,

I'm starting to look into references, but not everything is clear yet.

This is what I am trying to acheive: I have a list of scalars and I want to build multi-level hash from it (like tree structure).
[tt]
EG:

Given : @array = ("one","two","three");
Result : $hash{one}{two}{three}
[/tt]
This is the small code I wrote, but something is still wrong, probably in the resetting of the reference pointer.
[tt]
# Initialise variables
my @array = ("one","two","three");
my %hash = ();
my $hashref = \%hash;

# Loop for every element in @array
foreach (@array) {

# Add the $_ to hash
$$hashref{$_} = ();

# Redefine the reference pointer
$hashref = \%{$hash{$_}};

}
[/tt]

Can anybody help?

Thanks,

Thierry
 
$$hashref{$_} = ();

I don't think that does what you think. $hashref{$_} = (); says add an element to the hash %hashref, where the key is the value of $_, and the value is () (I don't know what that is - did you mean you wanted the value to be a new hash?).

You only need the leading dollar sign in $$hashref{$_} = (); if the value of $hashref{$_} is a reference that you want to dereference.

Maybe a look from a different angle will help:

my %hash = (
"aaa" => {
"date" => "Date string",
"hostname" => "Hostname string"
},

"bbb" => {
"foo" => "foo string",
"bar" => "bar string"
}
);

foreach $key (keys %hash) {
print "\n";
print &quot;key=<$key>\n&quot;;

foreach $cmd (keys %{$hash{$key}}) {
print &quot; cmd=<$cmd>, string=<$hash{$key}{$cmd}>\n&quot;;
}
}

---------------------------------------
That prints out:

key=<aaa>
cmd=<date>, string=<Date string>
cmd=<hostname>, string=<Hostname string>

key=<bbb>
cmd=<foo>, string=<foo string>
cmd=<bar>, string=<bar string>

HTH.
Hardy Merrill
Mission Critical Linux, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top