Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to do addition/multiplication with in the hash

my %g_tun = qw ( R1 100*32+1 R2 1 R3 100*32+1 ); print "G is $g_tun{R1}\n";

Output is this. GRE is 100*32+1 Is there a way to do the expression with in the hash value itself

Replies are listed 'Best First'.
Re: Expression inside hash
by 1nickt (Canon) on Apr 03, 2016 at 18:23 UTC

    qw() quotes "words" so your expression is not being evaluated. See perlop : Quote and Quote-like Operators for more info.

    Try:

    my %g_tun = ( "R1", 100*32+1, "R2", 1, "R3", 100*32+1 );
    or:
    my %g_tun = ( R1 => 100*32+1, R2 => 1, R3 => 100*32+1, );

    Hope this helps!


    The way forward always starts with a minimal test.

      Thanks.That worked

Re: Expression inside hash
by Athanasius (Archbishop) on Apr 04, 2016 at 03:47 UTC

    If you want to evaluate each expression and then store the result in the hash, 1nickt’s answer is what you’re looking for. But if you want to store unevaluated expressions in the hash and evaluate them later, you need the “string eval” form of eval:

    use strict; use warnings; my %g_tun = qw( R1 100*32+1 R2 1 R3 100*32+1 ); printf "G is %d\n", eval "$g_tun{R1}";

    Output:

    13:43 >perl 1584_SoPW.pl G is 3201 13:45 >

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,