in reply to Re: variable inside hash key
in thread variable inside hash key

I think increment of $pic is not happening with this method

my $pic = 1; my $key_MS = "R3R3_${pic}_IF"; my $temp = 90; for (my $ip = 1; $ip<=100; $ip++) { if ($temp == $ip) { $pic++; } } print "New pic value is $key_MS\n"; output:New pic value is R3R3_1_IF

Replies are listed 'Best First'.
Re^3: variable inside hash key
by hippo (Archbishop) on Apr 06, 2016 at 08:47 UTC

    $pic is being incremented. This however has absolutely no effect on $key_MS which was set and evaluated when $pic was still 1. If you want to have it re-evaluated every time it is referenced you would need a closure or an eval or similar. eg. (with the loop replaced for clarity)

    #!/usr/bin/env perl use strict; use warnings; my $pic = 1; my $key_MS = sub { "R3R3_${pic}_IF"; }; print "Old pic value is " . &$key_MS . "\n"; $pic = 2; print "New pic value is " . &$key_MS . "\n";

      The problem with this is, i need to use the output &$key_MS, with in a hash key and it may not work

      my $key_MS = sub { "R3R3_${pic}_IF"; }; print "set service-interface $v->{&$key_MS}.0\n";

        Works for me. But when in doubt, use the . concat operator, like in the second example below, or in the case of print, the comma operator like in the third example. Otherwise, please be more specific than "it may not work", and provide a piece of example code where it fails (see How do I post a question effectively?).

        my $v = { R3R3_1_IF=>"xx", R3R3_2_IF=>"yy", R3R3_3_IF=>"zz" }; my $pic = 1; my $key_MS = sub { "R3R3_${pic}_IF"; }; print "set service-interface $v->{&$key_MS}.0\n"; $pic++; print "set service-interface " . $v->{&$key_MS} . ".0\n"; $pic++; print "set service-interface ", $v->{&$key_MS}, ".0\n"; __END__ set service-interface xx.0 set service-interface yy.0 set service-interface zz.0