in reply to Re: create an anonymous hash using "map"
in thread create an anonymous hash using "map"

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

In case it further helps your general understanding of BEGIN blocks in Perl, I've listed a few more references below:

Note that a use Module qw/a b c/; statement is equivalent to:

BEGIN {
   require Module;
   Module->import(qw/a b c/);
}

while sub name {...} is equivalent to:

BEGIN {
   *name = sub {...};
}

update: but see response by ikegami for how to name the BEGIN block anon sub (useful in traces).

PM References Added Later

👁️🍾👍🦟

Replies are listed 'Best First'.
Re^3: create an anonymous hash using "map" (BEGIN block References)
by perlfan (Parson) on Aug 24, 2024 at 17:58 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

Re^3: create an anonymous hash using "map" (BEGIN block References)
by ikegami (Patriarch) on Apr 29, 2025 at 22:14 UTC

    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