0

I'm using Perl, and I want to create variables in loop. So each loop will create me a variable with diffrent numeration. for example the first loop will create:

num1 = x;

the second loop will create

num2 =x;

Thanks for any help

2 Answers 2

6

Use an array and add a number each iteration.

my @nums;

for (1..10) {
    push @nums, $_; # your `x'
}
Sign up to request clarification or add additional context in comments.

3 Comments

There is any way to do it without arrays?
@adir — Yes, but it is evil, illogical, stupid, slow and a nightmare to debug. This is exactly what arrays are designed for.
@eugene y: Of course; that's only a simplified example compliant with the question, which deals with a loop.
6

If you really need to name them, then a hash should do as good. I don't recommend this, but you can do it. I'm simply showing you how to "name" things in a systematic way, in the same way you would use first-class variables.

my %hash;
my $i = 0;
for ( @list ) { 
    $hash{ 'num' . ++$i } = $_;
}

Again this is rather pointless to name numbers according to their order when an array does something similar, plus you never have to worry about lexicographical order getting in the way.

So you should think about the problem you are trying to solve by naming the variables, in order to decide whether that is the best way.


I just recalled what I have done when I wanted to type as little different from scalar syntax as possible. It relies on the fact that *_ is a glob, but there are certain slots not used in the GLOB.

So you can use local %_;

Thus there are only 3 extra characters to type with any of this type of psuedo-variable:

$_{num001} += 43;

Of course, this is the same amount of extra characters you have to type in

$v{num001} += 43;

as well.

2 Comments

while the sprintf makes it look a little over-complicated, I agree in principle: if you need to add named data to a pool of knowledge to be used later, use a hash. If instead you need an ordered set of data, use an array.
@JoelBerger, having had enough run-ins with lex order (usually, in other people's code), it's second nature to me to concat strings and numbers with a sprintf format spec.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.