Use a key which is the value of a constant in a hash in perl -


please check code below:

my %hash = ( 123 => "a", 456 => "b", );  use constant x_1 => 123; use constant x_2 => 456; 

i want use $hash{x_1} "a". tried store x_1 variable , use key, worked.

my $var = "x_1"; # or $var = x_1 

but when variable x_1 array store variable, , try access hash variable, shows error.

my @arr; $arr[0]{"y_1"} = "x_1"; $arr[0]{"z_1"} = "x_2"; $newvar = $arr[0]{"y_1"};#$newvar = x_1 print $hash{$newvar}; #this shows error. 

how use variable not string constant here?

i want use $hash{x_1} "a"

by using identifier, expression won't autoquoted. example, use of following:

  • $hash{+constant}
  • $hash{(constant)}

so use $hash{+x_1} instead of $hash{x_1}.


how use variable not string constant here?

you rightfully ask prevented doing adding use strict; because it's dangerous (meaning hard read, hard debug, hard maintain, etc, etc, etc).

solution 1: use lookup table.

my %lookup = (    x_1 => x_1,    x_2 => x_2, );  @arr; $arr[0]{"y_1"} = "x_1"; $arr[0]{"z_1"} = "x_2";  $newvar = $arr[0]{"y_1"}; defined( $key = $lookup{$newvar} )    or die("invalid key");  print $hash{$key}; 

solution 2: use constant's value instead of name.

my @arr; $arr[0]{"y_1"} = x_1; $arr[0]{"z_1"} = x_2;  $newvar = $arr[0]{"y_1"}; print $hash{$newvar}; 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -