in reply to Anonymous subroutines

Bod, forgive me for making a guess, but are you familiar with the concept of "closures" in computer programming? If not, I suggest you read these basic links:

Once you understand the concepts, the code you saw with "anonymous subroutines declared for no apparent reason" might make more sense. Feel free to point us at some specific examples you saw.

👁️🍾👍🦟

Replies are listed 'Best First'.
Re^2: Anonymous subroutines (Closures)
by LanX (Saint) on Dec 11, 2023 at 09:33 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