Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have just begun to use subroutines for my scripts and I have stumbled across the following :

In the following code I declared the $variable input via my in a while() loop. Now I want to access this variable in the "outer" block without having to declare it globally. So that it's just available to the "input" subroutine. How can I accomplish this?
sub input { while ( 1 ) { my $input = <STDIN>; chomp ( $input ); if ( $input !~ /\d/ ) { print "ILLEGAL INPUT\n"; next; } last; } return $input; }
Thanks for your help

Replies are listed 'Best First'.
Re: my() troubles
by lemming (Priest) on Feb 14, 2001 at 04:22 UTC
    Instead of where you use "last;" You could use "return $input;" on that line or use the example below.
    I wrote this replacement code
    sub input { my $input; print "ILLEGAL INPUT $input\n" while ( chomp($input = <STDIN>) and $input !~ /^\d+$/); return $input; }
    I changed it slightly in that it will only return input if $input is a number. Your example would return "spam9" as good input.
Re: my() troubles
by dvergin (Monsignor) on Feb 14, 2001 at 10:50 UTC
    To stay closer to your original example, try separating the 'my' statement from the value assignment:
    sub input { my $input; # Just the 'my' here while ( 1 ) { $input = <STDIN>; # Asssignment here chomp ( $input ); if ( $input !~ /\d/ ) { print "ILLEGAL INPUT\n"; next; } last; } return $input; }

    Now the scope of '$input' is the entire sub block and 'return $input;' will work.

Re: my() troubles
by a (Friar) on Feb 14, 2001 at 10:43 UTC
    If I've got your question correctly,
    my $digit_input = &input;
    that is (in the sub);
    return $input;
    makes the sub input give back the value of $input.

    a