19. Variable: how-to


1. Create variablenames dynamically

An example of dynamically created variable names can be found in e.g. Javascript programming:


   let k = 'value';
   let i = 0;
   for (i = 0; i < 5; i++) {
     eval('var ' + k + i + ' = ' + i + ';'); #result e.g. var value0 = 0;
   }
   console.log("value0 = " + value0);   
   console.log("value1 = " + value1);
   console.log("value2 = " + value2);
   console.log("value3 = " + value3);
   console.log("value4 = " + value4);   
In Perl you should not do this, then Perl has an excellent answer: a hash!

    %value=();

    for ($i = 0; $i < 5; $i++) {
      $value{$i} = $i;
    }

    for ($i = 0; $i < 5; $i++) {
      print("value$i = $value{$i}\n");
    }

2. How to add a number to letters?

$str = "A B C";
$str =~ s/([A-Z]+)/${1}0/g;
print("Result: $str\n"); A0 B0 C0
Notice that the curly braces in ${1} are essential: without them the code does not run.