in reply to Re: Anonymous subroutines (Closures)
in thread Anonymous subroutines

Yes anonymous subs are often closure subs.

But to avoid a common misunderstanding:

In Perl at least. :)

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

PS: I'm not too sure about that part of the FAQ (at least in Python3)

> "Note that some languages provide anonymous functions but are not capable of providing proper closures: the Python language, for example." °

update

°) I think the FAQ should be fixed, see https://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python . Even in python2 it's possible, just "hackier"

Replies are listed 'Best First'.
Re^3: Anonymous subroutines (Closures)
by choroba (Cardinal) on Dec 13, 2023 at 10:23 UTC
    > I think the FAQ should be fixed

    perlfaq#114

    > Even in python2 it's possible, just "hackier"

    The fact that you need to use a list instead of an integer makes it more of impossible than possible. ;-)

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      AFAIK there are 3 issues with translating Perl closures to Python2

      • no block scopes °
        workaround: use function bodies
      • implicit declaration by assignment °
        workaround: you need a dict (hash) for changeable closure vars. So var++ becomes dict["var"]++ , Py3 introduced nonlocal var
      • lambdas are limited to one statement only
        workaround: every non trivial subroutine must be named. But this is helped by the fact that lexical subs and nesting of subs are the default in Python. Perl later introduced my sub for this

      I have trouble imagining a closure in Perl which can't be translated with one-to-one semantics. Of course with more lines...

      That idiomatic things become sometimes bloated in the process is normal, in both directions. (Especially you'll need a lot of named subs in Python, OTOH naming can make the code more self documented.)

      > more of impossible than possible. ;-)

      If you think otherwise please gimme an example of a hard to translate closure.

      update

      °) Another issue in Python is variable-hoisting ,tho Pythonistas don't seem to understand the subtle Action at a distance problem resulting from that.

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