Reputation: 77
I am declaring a variable like -
for($i = 0; $i <= 3; $i++)
{
if(some condition) {
my ${'file'.$i.'size'} = 0; }
}
I want my variable to be only declared if it matches the condition else not. I expected it to create 4 variables like file1size file2size etc. However I am getting error "Can't declare scalar dereference in my perl". Where am I going wrong ?
Upvotes: 1
Views: 181
Reputation: 386331
You can dynamically create package variables names (as opposed to lexical (my
) variables), but it's a horrible idea. It's so bad that we use use strict;
to tell Perl to forbid us from doing it.
You are effectively building an array.
my @file_sizes;
for my $i ( 0 .. 3 ) {
if ( some condition ) {
$file_sizes[ $i ] = 0;
}
}
Whether this makes sense is another question.
Just like your original code, this creates "holes", by which I mean indexes with no value (undef
for value). This, by itself, it not necessary wrong. But what's the point of an array that contains 0, undef, 0
? or undef, 0, 0
? (Even if the zeroes are other numbers.) Maybe you have parallel arrays. It might make sense in that case. But it's hard and annoying to work with parallel arrays, and that makes them error-prone.
So again, this code looks really fishy. But I have no information that I can use to improve it.
Upvotes: 2