Perl: Create alphanumeric sequencial vars

280 Views Asked by At

I would like to ask a help to create a Perl code where I could create alphanumeric sequential vars (that could be used as array, hash or any other kind of var).

for ( my $x = 1; $x <= 10; $x++ ){
  my $var$x = "" *# to create empty variable with the word 'var' + the integer from x (var1, var2, var3, ...)* 
  for ( my $y = 1; $y < 10; $y++){
    my $var$x = $var$x.''.$x.''.$y *# to store/concatenate the values from $x+$y into var$x*
  }
  print "$var$x"
}

What should print:

var1 = 11, 12, 13, 14, 15, 16, 17, 18, 19
var2 = 21, 22, 23, 24, 25, 26, 27, 28, 29

and so on

Thank you

2

There are 2 best solutions below

2
On BEST ANSWER

What you are asking for is a very bad idea. You want to create a variable, using the value of another variable as part of the name. This is known as "symbolic referencing" and there is a very good reason why it is one of the three things that use strict turns into a fatal error.

For a good discussion of the problems it can cause, see these three articles by Mark Dominus.

Almost certainly, the best solution to your problem is to use an array, hash or some other (more complex) data structure. But without knowing a lot more about what you're doing it is hard to make any concrete suggestions.

0
On

Don't try to generate variable names!

All you need is

for my $x (1..10) {
   for my $y (1..9) {
      print "$x$y\n";
   }
}

Or if you want to populate a data structure instead of printing,

my @matrix;
for my $x (0..9) {
   for my $y (0..8) {
      $matrix[$x][$y] = ($x+1).($y+1);
   }
}

Same as previous:

my @matrix;
for my $x (1..10) {
   my @row;
   for my $y (1..9) {
      push @row, "$x$y";
   }

   push @matrix, \@row;
}