7

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 while 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 ;
1
  • $i = 1; should probably be my $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 under use strict; use warnings; then the strict pragma would have thrown an error about the undeclared variable. Commented Jul 14, 2010 at 21:43

3 Answers 3

10

You declare variable test inside the loop, so it scope is the loop, as soon as you leave the loop the variable is not longer declared.
Add my $test; just between $i=1 and while(..) and it will work. The scope will now be the entire sub instead of only the loop

Sign up to request clarification or add additional context in comments.

1 Comment

ahh ok, I get it now.. thanks... the tutorials I've been looking at are too basic to even have mentioned this, I suppose I should go straight to the perl man pages from now on
5

Place my $test before the while loop. Note that it will only contain the last value that is assigned in the while loop. Is that what you are after?

// will print "it's working" when 'the loop is hit at least once,
// otherwise it'll print "it's not working"
sub testthis {
    $i = 1;
    my $test = "it's not working";

    while ($i <= 2) {
        $test = "it's working";
        $i++ ;
    }
    print $test ;
}

Comments

3

you can try this one:

sub testthis {
my $test
$i = 1;
while ($i <= 2) {

$test = 'its working' ;

$i++ ;

print $test ;
}

}

&testthis ;

Note: whenever write perl code, its better to add use strict; and use warning in the beginning of the code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.