Dynamically Generate Variable Names in Perl

NOTE: this is not recommended, but it is a powerful feature which can be useful.

We can generate dynamic variable names in Perl using Symbolic References. To use the feature, we have to turn off strict refs.

The code below generates the variable names ‘var1’, ‘var2’, ‘var3’ dynamically in a loop as strings, names which can be used as actual variable names with the help of symbolic references.
Of course, hashes should be used instead whenever possible; this is for demonstration.

use strict;
 
our $var1 = 'a';
our $var2 = 'b';
our $var3 = 'c';

for (my $i = 1; $i < 4; $i++) {
  my $variableName;
  {
    # Symbolic References require 'no strict'.
    no strict 'refs';
    $variableName = ${'var' . $i}; # Dynamic name.
  }
  print $variableName . "\n";
}

Output:

a
b
c

 

Leave a Reply

Your email address will not be published. Required fields are marked *