Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   Perl (https://www.askmehelpdesk.com/forumdisplay.php?f=453)
-   -   Dynamic Variable Names (https://www.askmehelpdesk.com/showthread.php?t=232887)

  • Jul 1, 2008, 05:03 PM
    theterabyteboy
    Dynamic Variable Names
    I am wondering how to create a variable with a variable name in it.

    Ultimately what I want to do is:

    my $frequency1 = $frequency;
    my $frequency2 = $frequency;
    my $frequency3 = $frequency;

    but the line my $frequency# = $frequency occurs inside of a loop and I can only
    use this instruction once and want to set the value of the appropriate frequency variable.

    I have a variable named $attempts and attempts holds the value 1, then 2, and then 3 on the third iteration of the loop

    I am trying to use some sort of command like:

    my $frequency{$attempts} = $frequency;

    but this is not working, can someone please help? Thank you very much.
  • Jul 5, 2008, 12:01 PM
    derobert
    You can refer to non-my variables by name, the syntax looks like this:

    $frequency2 = 10;
    my $var_name = "frequency2";
    print $$var_name, "\n";

    but you probably don't want to. If you have a list of frequencies, you probably want to use an array. E.g.

    my @frequencies = (10, 20, 30);

    for (my $i = 0; $i < 2; ++$i) {
    print $frequencies[$i], "\n";
    }

    Or, you could use foreach, map, etc. to iterate over the array.

  • All times are GMT -7. The time now is 07:49 AM.