Perl 6 docs contains a list of types. Some of them, for example Str
, have more complex box / unbox behavior.
Is it possible to define my own type by specifying my own procedures for box / unboxing? For a specific project, I have many types that I reuse, and basically cut / paste my access functions over and over again.
For example, C Struct uses time_t
, and I connect access methods to go to / from DateTime
. Another example is a comma separated list, I would like to go to / from Array
and take care of split
/ join
automatically.
Is there a better way to do this?
Edit : Add an example:
constant time_t = uint64;
constant FooType_t = uint16;
enum FooType <A B C>;
class Foo is repr('CStruct') is rw
{
has uint32 $.id;
has Str $.name;
has FooType_t $.type;
has time_t $.time;
method name(Str $n?) {
$!name := $n with $n;
$!name;
}
method type(FooType $t?) {
$!type = $t with $t;
FooType($!type);
}
method time(DateTime $d?) {
$!time = .Instant.to-posix[0].Int with $d;
DateTime.new($!time)
}
}
my $f = Foo.new;
$f.id = 12;
$f.name('myname');
$f.type(B);
$f.time(DateTime.new('2000-01-01T12:34:56Z'));
say "$f.id() $f.name() $f.type() $f.time()";
, CStruct
Perl-ish ( lvalue, ).
time_t
, FooType_t
.. . , ?
, ? .