cannot acces variable inside while loop (in perl)
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 i开发者_StackOverflow社区n a naked block I follow with the error.
{
my $my_variable;
while(<FILE>) {
...using $my_variable
}
if ($my_variable) -> FAILS
}
Any suggestion?
Are you using
$my_variable
in the loop or did you redefine it asmy $my_variable
somewhere in the loop. You'd be surprised how easily amy
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.- I wouldn't worry about initializing all my variables -- but its crucial that you learn a mindset about how to use undefs. And always, always USUW (
use strict; use warnings
) so that variables aren't uninitialized when you don't expect them to be.
Do you ever assign to $my_variable
? All you show is a declaration (the my
) and a usage (the if
) but never an assignment.
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.
精彩评论