#!/perl -w
# NAME: test-eval.pl
# AIM: test generation of variables, and gettting their value
# This would also work for calling subroutines
# 2009/10/24  - geoff mclane - http://geoffair.net/mperl/
use strict;
use warnings;

my $var1 = "Variable 1";
my $var2 = "Variable 2";
my $var3 = "Variable 3";
my $var4 = "Variable 4";

sub prt($) {
    print shift;
}

sub test1() {
    my ($i, $tmp, $val, $nval,$tmp2,$str);
    for ($i = 1; $i <= 5; $i++) {
        $tmp = "\$var"."$i";
        #$tmp2 = \$var."$i";
        #prt("$tmp\n");
        #$val = eval ($tmp);
        $val = eval $tmp;
        if (defined $val) {
            prt("$i: Value of $tmp = [$val]\n");
            $nval = "New value $i";
            #eval ($tmp = "New value $i");   # this does NOTHING!!!
            #eval (*$tmp = $nval);   # this does NOTHING!!!
            #eval ($tmp = "other");
            #eval '$tmp = $nval';
            #eval { $tmp = $nval; };
            #eval { ${$tmp} = $nval; };
            #${$tmp} = $nval;
            $str = "$tmp".' = $nval';
            #prt("$str\n");
            eval $str;
        } else {
            prt("$i: $tmp NOT DEFINED!\n");
        }
    }
    for ($i = 1; $i <= 5; $i++) {
        $tmp = "\$var"."$i";
        $val = eval ($tmp);
        if (defined $val) {
            prt("$i: Value of $tmp = [$val]\n");
        } else {
            prt("$i: $tmp NOT DEFINED!\n");
        }
    }
}

sub test2() {
    # put some code inside $str
    my ($c);
    my $str = '$c = $a + $b'; # Perl doesn't care what's inside $str
    my $a = 10;
    my $b = 20;
    eval $str;             # Treat $str as code, and execute it.
    prt("Value of c = $c\n");              # prints 30
}
#########################################
### MAIN ###
test1();
test2();
exit(0);
########################################
# eof - test-eval.pl
