0

hi i've read some related question non seems tohelp me. this is a code that will explain what i want.

for ($i=0;$i<5;$i++) {
  my $new$i=$i;
  print "\$new$i is $new$i";
}

expecting variables to be named $new0,$new1,$new2,$new3,$new4,$new5. and to have the abillty to use them in a loop like the print command is trying to do. Thanks

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Chaggster
  • 2,441
  • 3
  • 21
  • 14

5 Answers5

18

You want to use a hash or array instead. It allows a collection of data to remain together and will result in less pain down the line.

my %hash;
for my $i (0..4) {
    $hash{$i} = $i;
    print "\$hash{$i} is $hash{$i}\n";
}
Schwern
  • 153,029
  • 25
  • 195
  • 336
11

Can you describe why exactly you need to do this. Mark Jason Dominus has written why doing this is not such a good idea in Why it's stupid to "use a variable as a variable name" part 1, part 2 and part 3.

If you think your need is an exception to cases described there, do let us know how and somebody here might help.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Gurunandan Bhat
  • 3,544
  • 3
  • 31
  • 43
9

You are asking a common question. The answer in 99.9% of cases is DON'T DO THAT.

The question is so common that it is in perlfaq7: How can I use a variable as a variable name?.

See "How do I use symbolic references in Perl?" for lots of discussion of the issues with symbolic references.

Community
  • 1
  • 1
daotoad
  • 26,689
  • 7
  • 59
  • 100
2

use a hash instead.

my %h=();
$new="test";
for ($i=0;$i<5;$i++) {
  $h{"$new$i"}=$i;
}
while( my( $key, $value ) = each( %h ) ) {
    print "$key,$value\n";
}
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
-4

if you want to create variables like $newN you can use eval:

eval("\$new$i=$i");

(using hash probably would be better)

catwalk
  • 6,340
  • 25
  • 16
  • 15
    No need for an eval, a symbolic reference is faster and safer. `${"new".$i} = $i`. But really, don't do that. – Schwern Dec 24 '09 at 12:50