>I've played
>tag the wall with the forehead long enough.
> a) a way to name a hash from user input
If you mean assign a value with in a hash using the user input, then:
my %hash
$key = <STDIN>;
$val = <STDIN>;
$hash{$key} = $val;
If you really want to let the user name your variables for you (which you
probably really don't want), you would use eval;
$hashname = <STDIN>;
eval ("\$$hashname;");
don't do that though...
> b) find a way to create a multi-level hash (hash within a hash)
This is done with references. They only seem hard at first.
here's a hash:
%happy_hash = (
"smile" => ":)",
"bigger" => ":D",
);
here's another:
%another_hash = (
"far" => "Look over There!",
"near" => "Look at this!",
);
now here's a third that holds the first two:
%big_hash = (
"happy" => \%happy_hash,
"another" => \%another_hash,
);
the back slash means that the variable refers to the hash, but is not
really the hash. This way you get a scalar (which is what hashes are made
of), but you can use it to get to the hash.
here's one syntax to get to the hash:
$big_smile = ${$big_hash{"happy"}}{"bigger"};
# you can probably get away with $big_hash{"happy"}{"bigger"},
# and it doesn't look as confusing, but I use the previous
syntax.
$big_hash{"happy"} returns the reference to the happy_hash, just as this
would assign it to a scalar:
$hrHappy = $big_hash{"happy"};
To dereference this to the hash is %{$big_hash{"happy"}}. Just wrap the
scalar in braces and stick the appropriate symbol on front ($%@&*)
for $hrHappy it's %{$hrHappy}
Now you can access the value in the hash; just like a regular hash, but
with a weird lookin' name. The syntax is $hashname{key}, so here it's
${$big_hash{"happy"}}{"bigger"} or ${$hrHappy}{"bigger"}, both of which
return $happy_hash{"bigger"}, which is ":D"
Ofcourse, why put hashes that have names in other hashes unless you have a
good reason? So there are anonymous hashes. They look like this:
{"smile" => ":)", "bigger => ":D"}
and you can assign them just like a hash reference:
%big_hash = (
"happy" => {
"smile" => ":)",
"bigger" => ":D",
},
"another" => {
"far" => "Look over There!",
"near" => "Look at this!",
},
);
and create them on the fly too:
${$big_hash{"onion"}}{"burger"} = "beefy";
${$big_hash{"onion"}}{"ring"} = "greasy";
$big_hash{"foul"} = {"bird" => "duck", "ball" => "strike"};
And hopefully code that looked illegible before is starting to make some
sense.
>#Create a multi-dimensional array
same thing:
@big_arr = ([EMAIL PROTECTED], [EMAIL PROTECTED], [EMAIL PROTECTED]);
even:
@hash_arr = (\%hash1, \%hash1, \%hash1);
or:
@mixed_arr = (\%hash1, [EMAIL PROTECTED], \%big_hash, [EMAIL PROTECTED]);
There are lots of fun ways to build data structures using references. You
can create anonymous subroutines too, and put those in a hash.
HTH
-Peter
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]