It seems very simple, but itβs hard for me to understand, since I am new to perl. I was looking through a lot of documentation about loops, and I'm still shocked by this ... I have a sub that contains a while loop, and I want to use the value of the variable from the loop outside the loop (after the loop has been started), however when I try to print the variable or return it from sub, it does not work, only when I print the variable from the loop, it will work. I would appreciate any advice regarding what I am 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 ;
variables scope loops perl while-loop
Rick
source share