anon
ErrorsCollection

anon

Synthesised documentation from language/variables

From language/variables

See Original text in context

The anon declarator prevents a symbol from getting installed in the lexical scope, the method table and everywhere else.

For example, you can use it to declare subroutines which know their own name, but still aren't installed in a scope:

my %operations =
    half   => anon sub half($x{ $x / 2 },
    square => anon sub square($x{ $x * $x },
    ;
say %operations<square>.name;       # square 
say %operations<square>(8);         # 64

Since it is a declarator, it can be applied anywhere anything is declared, for instance for classes or even sigilless variables.

say anon class þ {};     # OUTPUT: «(þ)␤» 
say anon sub þ  { 42 };  # OUTPUT: «&þ␤»

Since these symbols are not installed in the scope, they can't be used by name. They are useful, however, if they need to be assigned to an external variable and they need to know their own name, but this can be retrieved using introspection.

my $anon-class = anon class {
    has $.bar;
    method equal( ::?CLASS $foo ) {
      return $foo.bar == $.bar;
    }
};
say $anon-class.new:3bar).equal$anon-class.new:3bar ) );
# OUTPUT: «True␤»