http://qs1969.pair.com?node_id=215933

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

Hello,
I am trying to have my script go through some
variables without the variable names being there until
the code is run. I think this is late-binding but i am
not entirley sure. Here is what i want to do.
my result_temp=""; foreach my $test (@testarray) { if(!defined($result_temp = $session->getrequest( -varbindlist => ['$'.%cmd_table{$test}] ))) { print ("error in session:%s", %cmd_table{$test}); $result_temp="error"; } push @RESULTS, @result_temp; }
What the code would look like that is late-bound is
-varbindlist => [$myvariable]
but what will the perl interpreter see?
cause the variable names are all in cmd_table hash
referenced by a number (where test_array is a array of
command numbers. Is there a way to so what i want?
Thanks.
Enigmae

Replies are listed 'Best First'.
Re: using variables in late contexts?
by Eimi Metamorphoumai (Deacon) on Nov 26, 2002 at 22:46 UTC
    Although the other replies will probably work, the idea is probably misguided. There are very, very few places where it's a good idea to use variables for variable names, and this isn't one of them. Try to rewrite your code using a hash instead. See mjd's excellent post for more information.
Re: using variables in late contexts?
by robartes (Priest) on Nov 26, 2002 at 22:37 UTC
    Your code should work, except that you need to replace:
    %cmd_table{$test}
    by
    $cmd_table{$test}
    You are refering to the value of a hash entry, not the hash itself, that's why you need $.

    Oh, and there is no need for the @testarray (at least not in this snippet): just loop over the keys of %cmd_table, as in:

    foreach $test (keys %cmd_hash) { # do your thing }
    Hope this helps.

    CU
    Robartes-

Re: using variables in late contexts?
by jreades (Friar) on Nov 26, 2002 at 22:34 UTC

    Let me see that I have this straight.

    You want your code to 'look' like:

    -varbindlist => [$myvariable]

    Where the input would be:

    -varbindlist => [${$some_variable}]

    And the input $some_variable would be derived from a value in %cmd_table.

    In that case, I think that the answer is simply:

    my @RESULTS = (); my $test; foreach $test (@test_array) { my $temp = $session->getrequest( -varbindlist => [${$cmd_table{$test}}] ); unless (defined $temp) { print("Error in session: %s", $cmd_table{$test}); push @RESULTS, "error"; } else { push @results, $temp; } }

    Reformat for personal style.

    Also note that this will probably cause some issues if you use strict since you're interpolating variable names which could result in various security issues.