Search code examples
perlvariablessubroutine

Undefined variables in Perl subroutines


I am new to Perl and would like some help in understanding subroutines. In subroutines, is it the case that some variables will always be undefined? Is this because variables in subroutines are private? And so what if I wanted to then define said previously undefined variable, how would I go about doing that? Thanks in advance.


Solution

  • Variables in Perl are not private, but they can have a limited scope. Such as when declaring them with my inside a subroutine. The arguments to the subroutine are stored in the variable @_.

    do_stuff($foo, $bar);
    
    sub do_stuff {
        my ($first, $second) = @_;   # direct assignment
        print "First: $first, Second: $second\n";
    }
    

    The my declaration makes the variables lexically scoped to the surrounding block { ... }, which means they are protected, and they go out of scope when execution leaves the block.

    Arguments to subroutines can also be accessed with the array functions shift and pop, which is commonly seen in Perl code:

    sub do_stuff {
        my $first   = shift;
        my $second) = shift;    
    

    This does the same thing, except that it also removes the elements from the @_ array.

    Read more: