Search code examples
perldynamic-variables

How to assign a value to a variable with a dynamically created name?


I know this is a no-no...and yes, I still want to do it or at least know how to do it. I would like to set the value of a variable in Perl for which the name is dynamically created (I am looping through different arrays of strings). I know I could do it rather straightforwardly with a hash array, but I'm just curious how you do this with a scalar variable, e.g.

$time  = 't0';
$color = 'blue';

I want to create the variable

$bluet0 = 1;

I've tried

${time.$color} = 1 

but that doesn't work.


Solution

  • Replace

    ${ time . $color } = 1;
    

    with

    no strict qw( refs );
    
    ${ $color . $time } = 1;
    

    Like you said, this is something to avoid.