Reputation: 1720
A very easy question on variables scope. I have a variable defined in the main code that I use inside a while loop.
my $my_variable;
while(<FILE>) {
...using $my_variable
}
if ($my_variable) -> FAILS
When I exit the loop and use the variable I get an error:
Use of uninitialized value $my_variable
Even if I enclose the variable in a naked block I follow with the error.
{
my $my_variable;
while(<FILE>) {
...using $my_variable
}
if ($my_variable) -> FAILS
}
Any suggestion?
Upvotes: 0
Views: 2301
Reputation: 29854
Are you using $my_variable
in the loop or did you redefine it as my $my_variable
somewhere in the loop. You'd be surprised how easily a my
slips in to variable assignment.
I even have a frequent tick in my code where I write something like
my $hash{ $key } = ... some elaborate assignment;
Also, if
should not complain about an uninitialized variable. undef
=> Boolean false.
use strict; use warnings
) so that variables aren't uninitialized when you don't expect them to be.Upvotes: 1
Reputation: 91385
In the examples given, you didn't initialize $my_variable
so it is undefined after the while loop.
You can do my $my_variable = '';
just before the loop.
Upvotes: 0
Reputation: 15189
Do you ever assign to $my_variable
? All you show is a declaration (the my
) and a usage (the if
) but never an assignment.
Upvotes: 1