15

Is there a simple way to use the value of a defined constant as a hash / pair key in Perl6?

For instance :

constant KEY = "a string";
my %h = ( KEY => "a value" );

This will creatre a key of "KEY" not "a string".

I can do :

my %h = ( "{KEY}" => "a value" );

But that seems a bit clunky. I was wondering if there was a better way?

Pat
  • 36,282
  • 18
  • 72
  • 87
Scimon Proctor
  • 4,558
  • 23
  • 22

1 Answers1

16

The most convenient options would be to either:

  • Declare the constant with a sigil (such as constant $KEY = "a string";), thus avoiding the problem in the first place
  • Wrap the left hand side in parentheses (like (KEY) => "a value"), so it won't be treated as a literal
  • Write it instead as pair(KEY, "a value")

Also, note that:

my %h = ( "{KEY}" => "a value" );

Is a useless use of parentheses, and that:

my %h = KEY, "a value";

Will also work, since non-Pairs in the list of values to assign to the hash will be paired up. It loses the visual pairing, however, so one of the previously suggested options is perhaps better.

Jonathan Worthington
  • 29,104
  • 2
  • 97
  • 136