How do I create new variables with indexed names in Perl?
hi i've read some related question non seems tohelp me. this 开发者_StackOverflow中文版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
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";
}
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.
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.
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";
}
if you want to create variables like $newN you can use eval
:
eval("\$new$i=$i");
(using hash probably would be better)
精彩评论