Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading constants in Perl 6

Is it possible to overload constants in Perl 6? Here is the Perl 5 example I'm looking at.

In particular I would like to get a string of the literal value used, e.g. if the code was

my $x = .1e-003 ;

I need ".1e-003" instead of 0.0001.

like image 636
user2660278 Avatar asked Dec 15 '22 18:12

user2660278


2 Answers

I just added such a module:

https://github.com/FROGGS/p6-overload-constant

USAGE:

use v6;
sub decimal { $^a.flip }
use overload::constant &decimal;

say .1e-003 # "300-e1."
like image 90
Tobias Leich Avatar answered Dec 17 '22 06:12

Tobias Leich


You can change how a value stringifies by mixing in an appropriate role with the but operator, ie

0.0001 but role { method Str { ".1e-003" } }

which can be shortened to

0.0001 but ".1e-003"

Note that providing a method Stringy instead of Str might actually be more appropriate from a semantic point of view, but I do not think Rakudo as of today handles that distinction correctly in all case.

like image 26
Christoph Avatar answered Dec 17 '22 07:12

Christoph