Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl hash referencing itself at declaration

Tags:

perl

When declaring a Perl hash, I'm wondering if it's possible to use a value that was assigned earlier in the declaration.

I'd like to do the equivalent of this, all in one shot:

my %H   = (something => generateString());
$H{foo} = $H{something} . "/FOO",
$H{bar} = $H{something} . "/BAR",

I can imagine something like this:

my %H = (
   something => generateString(),
   foo       => $_{something} . "/FOO",
   bar       => $_{something} . "/BAR",
);

EDIT: To be clear, I don't care about an actual reference to $H{something} (i.e. changing $H{something} later shouldn't affect $H{foo}). I'd just like to get its value into the string concatenations.

like image 255
ajwood Avatar asked Dec 05 '25 12:12

ajwood


1 Answers

You seem to think there are two assignment operators in

%H = ( a=>1, b=>$H{a} );

There isn't. Keep in mind the above is identical to

%H = ( 'a', 1, 'b', $H{a} );

There's one assignment operator, and before you can perform the assignment, you need to know what is going to be assignment.

What I'm saying is that the real problem with %H = ( a=>1, b=>$H{a} ); isn't one of scope; the real problem is that nothing been assigned to %H when you do $H{a}[1]. As such, $_{a} makes more sense than $H{a}.

The solution is simple:

my $something = generateString();
my %H = (
   something => $something,
   foo       => "$something/FOO",
   bar       => "$something/BAR",
);

  1. %H hasn't even been created yet!
like image 190
ikegami Avatar answered Dec 07 '25 15:12

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!