anurag86
anurag86

Reputation: 1687

Defining hash value depending on the hash itself in perl

I want to fix the following code in such a way so as to have the desired output as given below. But i find both the print statements dont work at same time.

Code:

our %HASH=(
    elem1=>["FD1","FD2",$arr_path[0]],
    elem2=>["FD4","FD5",$arr_path[1]],
);
my @arr_path=(
    "/abc/def/$HASH{elem1}[0].ctrl",
    "/abc/def/$HASH{elem1}[1].ctrl"
);

    print "\nPrinting path from HASH  :". $HASH{"elem1"}[2];
    print "\nPrinting path from arr_path  :". $arr_path[0];
    print "\n";

Obtained output:

Printing path from HASH  :
Printing path from arr_path  :/abc/def/FD1.ctrl

Desired output:

Printing path from HASH  :/abc/def/FD1.ctrl
Printing path from arr_path  :/abc/def/FD1.ctrl

Upvotes: 0

Views: 41

Answers (1)

Rob
Rob

Reputation: 791

You can't make two variables that depend on each other.

What you could do is something like:

our %HASH=(
  elem1=>["FD1","FD2",],
  elem2=>["FD4","FD5",],
);
my @arr_path=(
    "/abc/def/$HASH{elem1}[0].ctrl",
    "/abc/def/$HASH{elem1}[1].ctrl"
);

$HASH{elem1}[2] = $arr_path[0];
$HASH{elem2}[2] = $arr_path[1];

but that's a bit confusing.

I think that you need to re-think your data structures and fetch the data from one structure, calculating the dependent information that you need. (If performance is an issue, use memoization.)

Upvotes: 1

Related Questions