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
    See also The-'lexical_subs'-feature and try
    • my sub inner {...

    Which is part of the standard language now. :)

    > because the inner sub would get bound to one my variable

    Basically, it's a 1-to-n problem, because closures are supposed to be created many times.

    But named subs are only once assigned globally and bound to a type-glob in the current package (think our ) at compile time (think BEGIN {...} )

    Nowthe compiler sees the use of lexical variables from the outer scope, which potentially change with every invocation. (The former are not destroyed) and emits the "won't stay shared" warning.

    An anonymous closure sub OTOH would be assigned each time and have a deep-binding to the current outer scope.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery