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

Thanks for the reply, jwkrahn! I'm still not sure how to work this into a charnames alias list, though. This:
#!/usr/bin/perl use charnames ":alias" => { map { $_ => $char++ } 'first character', 'second character', 'third character' }; printf "First: %X; third: %X\n", ord("\N{first character}"), ord("\N{third character}");
produces the error:
Unknown charname 'first character' at ./mytest line 10, within string Execution of ./mytest aborted due to compilation errors.
So it accepts the syntax of the alias setup, but doesn't actually create the aliases.

If you're suggesting I use your assignment statement as written and then use your $characters variable to do the alias setup, I can't even find the right syntax for that. This gives syntax errors on the use charnames line, as I would expect (as did a couple variants I tried):

#!/usr/bin/perl $characters = { map { $_ => $char++ } 'first character', 'second character', 'third character' }; use charnames ":alias" => $characters;

Replies are listed 'Best First'.
Re^3: create an anonymous hash using "map" (compile time)
by LanX (Saint) on Aug 07, 2024 at 11:41 UTC
    Actually, there is a second issue besides constructing a literal anonymous hash, which is complicating your case.

    It's the difference between run time vs compile time behavior.

    use will execute at compile time, so does your construct. Any code you depend on to be run before must also be executed at compile time, like in a BEGIN block.

    See perlmod for more on execution phases.

    Update

    And here a suggestion which seems best to be maintained IMHO.

    (untested hack into mobile browser)

    my %characters; BEGIN { my $char = 0xE000; %characters = map { $_ => $char++ } ( 'first character', 'second character', 'third character' ); } use charnames ":alias" => \%characters;

    you may also consider putting your rather complicated specialized configuration array into a module of your own, which is executed with use

    This will automatically happen at compile time, and provide you with a clean interface

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