in reply to Anonymous subroutines
It's been ages so I'm fuzzy on the exact details but there was a common problem encountered with mod_perl (where people initially would frequently use the CGI compatibility wrapper) where people would have named subs nested and then got warnings about "variable $foo won't stay shared at ####" because the inner sub would get bound to one my variable while the outer would have a new one reallocated on its pad. Again, fuzzy but something like this (not that this is at all useful code) <handwave>
#!/usr/bin/env perl use 5.034; sub outer { my $foo = $_[0]; sub inner { say "foo: $foo"; } inner(); } outer( "bar" ); outer( "quux" ); sub outer2 { my $foo = $_[0]; my $inner = sub { say "inner2: $foo"; }; $inner->(); } outer2( "bar" ); outer2( "quux" ); __END__ foo: bar foo: bar inner2: bar inner2: quux
Having the inner sub be an anonymous sub makes it a proper closure.
Edit: And the reason this was a frequent problem under mod_perl was that the CGI compatibility wrapper (Apache::Registry I think?) would wrap up the entire CGI script into an anonymous sub that it would run during the content phase so any named subs in the script were then nested subs.
The cake is a lie.
The cake is a lie.
The cake is a lie.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Anonymous subroutines (lexical subs & "will not stay shared")
by LanX (Saint) on Dec 11, 2023 at 15:30 UTC |