in reply to Re^2: HTML::LinkExtor weirdness (scoping closures nested named subs)
in thread HTML::LinkExtor weirdness

This is why you don't nest named subs, the closure becomes "static"

perl -E " sub f{ my %g; sub g{say \%g; } g(); say \%g; \%g } say f(),$/ for 1 .. 4;"

perl -E ' sub f{ my %g; sub g{say \%g; } g(); say \%g; \%g } say f(),$/ for 1 .. 4; '

HASH(0xabd9c4) HASH(0xabd9c4) HASH(0xabd9c4) HASH(0xabd9c4) HASH(0x3f9b6c) HASH(0x3f9b6c) HASH(0xabd9c4) HASH(0x3f9b8c) HASH(0x3f9b8c) HASH(0xabd9c4) HASH(0x3f9b6c) HASH(0x3f9b6c)

By making the nested subroutine a variable (also known as an anonymous sub), the closure is dynamic

$ perl -lE " sub f{ my %g; my $g = sub {say \%g; $g{1}++}; $g->(); say \%g; \%g } say f(),$/ for 1 .. 4;"

HASH(0xabd9d4) HASH(0xabd9d4) HASH(0xabd9d4) HASH(0x3f9b1c) HASH(0x3f9b1c) HASH(0x3f9b1c) HASH(0x99b374) HASH(0x99b374) HASH(0x99b374) HASH(0x99b344) HASH(0x99b344) HASH(0x99b344)
  • Comment on Re^3: HTML::LinkExtor weirdness (scoping closures nested named subs)