1
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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Vicky Gupta
  • 576
  • 6
  • 13

3 Answers3

6

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" .

Corion
  • 3,855
  • 1
  • 17
  • 27
4

The syntax you are using is valid since 5.18, but you need to add use feature qw( lexical_subs ); to enable it.

use strict;
use warnings;
no warnings qw( experimental::lexical_subs );  # Needed before 5.26. Harmless in 5.26+
use feature qw( lexical_subs say );

sub fun2 {
    my $var2 = 10;

    my sub fun1 {
        say $var2;
        ++$var2;
    }

    fun1();
    say $var2;
}

fun2();

Before 5.18, you can use

use strict;
use warnings;
use feature qw( say );

sub fun2 {
    my $var2 = 10;

    my $fun1 = sub {
        say $var2;
        ++$var2;
    };

    $fun1->();
    say $var2;
}

fun2();

or

use strict;
use warnings;
use feature qw( say );

sub fun2 {
    my $var2 = 10;

    local *fun1 = sub {
        say $var2;
        ++$var2;
    };

    fun1();
    say $var2;
}

fun2();
ikegami
  • 367,544
  • 15
  • 269
  • 518
0

Shouldn't this be:

 my $fun1 = sub {
    print"$var2";
    $var2++;
};
BarneySchmale
  • 658
  • 1
  • 4
  • 10