🔬 75. my $x = $x in Perl 6

What happens if you’ll try to create a new variable and immediately initialise it by itself, as shown in the following test code:

my $x = $x;

This does not work (which is expected), but Perl 6 is so kind to the user  that it gives an error message prepared especially for this case:

===SORRY!=== Error while compiling:
Cannot use variable $x in declaration to initialize itself
------> my $x = $⏏x;
  expecting any of:
  term

Let us find the place in the code where the error message is triggered. This case is captured in the Grammar of Perl 6, at the place where variable is parsed:

token variable {
    . . .
    | <sigil>
      [ $<twigil>=['.^'] <desigilname=desigilmetaname>
        | <twigil>? <desigilname> ]
      [ <?{ !$*IN_DECL && $*VARIABLE && $*VARIABLE eq 
        $<sigil> ~ $<twigil> ~ $<desigilname> }>
          {
              self.typed_panic: 'X::Syntax::Variable::Initializer', 
              name => $*VARIABLE
          }
      ]?
    . . .
}

The condition to throw an exception is a bit wordy, but you can clearly see here that the whole variable name is checked, including both sigil and potential twigil.

The exception itself is located in src/core/Exception.pm6 (notice that file extensions were changed from .pm to .pm6 recently), and it is used only for the above case:

my class X::Syntax::Variable::Initializer does X::Syntax {
    has $.name = '<anon>';
    method message() {
        "Cannot use variable $!name in declaration to initialize itself"
    }
}

And that’s all for today. Rakudo Perl 6 sources can be really transparent sometimes! 🙂

One thought on “🔬 75. my $x = $x in Perl 6

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s