Perl 6 Variable Types and Modules

I’m still learning a great deal about Perl and its typing. One of the things you hear a lot is that, in Perl 6 everything is an object. I’m finding this to be true, and it has some oftentimes surprising results.

For example, I’ve recently been playing with the DBIish module which affords database connectivity. We all know that working with date and time types with database columns can be a real pain, getting the formatting of the strings to insert correctly, and interpreting those when selecting out.

Perl has a module called DateTime built in. You can say it’s a module. You can say it’s a data type. You can say it’s an object. PostgreSQL has a timestamp with timezone data type (amongst others).

In my data model class, I defined an object attribute as a DateTime data type, just to play around and see what would happen.

class Shoe {
    has Pkey     $.id;
    has Str      $.description is rw;
    has DateTime $.created is rw;

    method retrieve(Pkey :$id = $.id) {
        ...
        $.created = %row<created_timestamp>;
        say "Created in the year {$.created.year}";
        say "warranty expires {$.created.later(:2years)}";
        ...
   }

You don’t need to worry about creating a DateTime object, other than specifying that your class attribute will be a DateTime type. All the conversions to string, whether TO the database or FROM the database, get handled seamlessly.

Honestly, I didn’t expect this to work — but I’m very happy to never have to worry about date and time formats again, when dealing with database column types! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *