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

> 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]

Replies are listed 'Best First'.
Re^4: Anonymous subroutines (Closures in Python)
by LanX (Saint) on Dec 13, 2023 at 13:31 UTC
    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