Perl using a variable from a While loop inside a loop?

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 ; 
+6
variables scope loops perl while-loop
source share
3 answers

You declare a variable test inside a loop, so its scope is a loop, as soon as you leave the loop, the variable is no longer declared.
Add my $test; only between $i=1 and while(..) and it will work. Now the area will be complete, not just a cycle

+9
source share

Put my $test before the while loop. Note that it will only contain the last value that is assigned in the while loop. That's what you need?

 // will print "it working" when 'the loop is hit at least once, // otherwise it'll print "it not working" sub testthis { $i = 1; my $test = "it not working"; while ($i <= 2) { $test = "it working"; $i++ ; } print $test ; } 
+5
source share

you can try the following:

 sub testthis { my $test $i = 1; while ($i <= 2) { $test = 'its working' ; $i++ ; print $test ; } } 

& testthis;

Note: whenever you write perl code, it is better to add use strict; and use warning at the beginning of the code.

+3
source share

All Articles