Reputation: 801
I've got a perl script and a .config file and want to store some hashes in the config file with some variables as its value, then dynamically change them from my perl script.
Config File:
$hash{"hello"} = ["$blah", "$blah2"];
And my perl script:
if (-e ".config")
{
$blah = "hello";
$blah2 = "world!";
eval ('require(".config")');
$val1 = $hash{"hello"}[0];
$val2 = $hash{"hello"}[1];
print "$val1 $val2\n";
# Now I want to CHANGE blah and blah2
$blah = "world!";
$blah2 = "hello";
$val1 = $hash{"hello"}[0];
$val2 = $hash{"hello"}[1];
print "$val1 $val2\n";
}
But both prints show hello world!
as if the change didn't happen.. Am I missing something?
Thanks.
Upvotes: 0
Views: 1119
Reputation: 46245
(Strange... I've never seen a question of this sort previously, and then variations on it (which are different enough to clearly not be just a cross-post) appeared both here and on PerlMonks in the same day.)
The point you're missing is that
$hash{"hello"} = ["$blah", "$blah2"];
just copies the values of $blah
and $blah2
into (an anonymous array referenced by) $hash{hello}
. It does not create any lasting connection between the hash and $blah
/$blah2
.
As a side note, none of the quotes in that line serve any purpose. It would more commonly be written as:
$hash{hello} = [$blah, $blah2];
Or, if you want to create references so that $blah
and $hash{hello}[0]
are forever linked and changing one will also change the other:
$hash{hello} = [\$blah, \$blah2];
Note that in this case, you must not use quotes. Although "$blah"
and $blah
are equivalent, "\$blah"
and \$blah
are not - \$blah
gives you a reference to $blah
, but "\$blah"
gives you the literal string "$blah" with no variables involved at all.
Upvotes: 2