This seems really simple but it is giving me a hard time figuring it out as I'm new to perl.. I've been looking through a lot of documentation now about loops and I am still stumped by this... I have a sub that contains a where loop and I want to use a variable value from within the loop outside of the loop (after the loop has run), however when I try to print out the variable, or return it out of the sub, it doesn't work, only when I print the variable from within the loop does it work.. I would appreciate any advice as to what I'm doing wrong.
Doesn't work (doesn't print $test ):
sub testthis {
$i = 1;
while ($i <= 2) {
my $test = 'its working' ;
$i++ ;
}
print $test ;
}
&testthis ;
Works, prints $test:
sub testthis {
$i = 1;
while ($i <= 2) {
my $test = 'its working' ;
$i++ ;
print $test ;
}
}
&testthis ;
$i = 1;
should probably bemy $i = 1;
, the way it is right now, you are talking to the variable$i
in the outer scope which will be a source of errors as soon as you start calling subroutines from inside other subroutines. Chances are that$i
is not even declared in the outer scope, in which case you are talking to the package variable. If you were running underuse strict; use warnings;
then thestrict
pragma would have thrown an error about the undeclared variable. – Eric Strom Jul 14 '10 at 21:43