tags:

views:

124

answers:

5

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

A: 

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

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

(using hash probably would be better)

catwalk
No need for an eval, a symbolic reference is faster and safer. `${"new".$i} = $i`. But really, don't do that.
Schwern
+11  A: 

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.

Gurunandan
+2  A: 

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
+17  A: 

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
+9  A: 

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.

daotoad