in reply to create an anonymous hash using "map"

Thank you, everyone! I have somehow never needed a BEGIN block (or any of perl's named blocks) before, so it never would have occurred to me to even search there. But LanX's explanation for why it's needed makes sense to me.

Replies are listed 'Best First'.
Re^2: create an anonymous hash using "map" (BEGIN block References)
by eyepopslikeamosquito (Archbishop) on Aug 09, 2024 at 11:11 UTC
      The practical uses of BEGIN and END in Perl may be more apparent when you consider how these were first used in awk. Perl of course took that idea and ran with it. As a Perl programmer, understanding this part of awk helped, especially with one-liners.
        I'm not an expert in awk's BEGIN, but I suppose that's despite the name more accurately described as an INIT block in Perl.

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

      Nit: sub name {...} is almost equivalent to BEGIN { *name = sub {...}; }. The latter has no name associated with it, which matters in traces.

      $ perl -e' use Carp qw( croak ); sub foo { croak "bar" } foo(); ' bar at -e line 3. main::foo() called at -e line 4
      $ perl -e' use Carp qw( croak ); BEGIN { *foo = sub { croak "bar" }; } foo(); ' bar at -e line 3. main::__ANON__() called at -e line 4

      There are ways of naming the anon sub to get a BEGIN-using equivalent.

      $ perl -e' use Carp qw( croak ); use Sub::Util qw( set_subname ); BEGIN { *foo = set_subname "foo", sub { croak "bar" }; } foo(); ' bar at -e line 4. main::foo() called at -e line 5