Search code examples
perl

How to create sub inside a sub in perl?


sub fun2{
    my $var2 = 10;

    my sub fun1{
        print"$var2";
        $var2++;
    }
   fun1();
   print "$var2";
 }

 fun2();

I want to print 10 and 11, this code gives error "Experimental "my" subs not enabled at source_file", if I remove "my" keyword from "my sub fun1" then it gives error "Variable "$var2" will not stay shared at source_file.pl line"

How can we allow the inner sub to modify the data of the outer sub?


Solution

  • Lexical named subroutines are still (very) experimental in Perl. The easy approach is to use an anonymous subroutine instead, which will circumvent the problems of losing shared variables while still not being experimental:

    sub fun2{
        my $var2 = 10;
    
        my $fun1 = sub {
            print"$var2";
            $var2++;
        };
        $fun1->();
        print "$var2";
     }
    
     fun2();
    

    The problem of nested named subroutines not keeping access to shared variables has already been linked to at Perl: "Variable will not stay shared" .