Welcome to Day 5 of this lovely Perl 6 One-Liner Advent Calendar!
Today, we’ll answer the question of what’s the date today (and tomorrow we can talk about palindromes if you want).
So, to print the answer, you can use the following line of Perl 6 code:
DateTime.now.yyyy-mm-dd.say
It looks transparent and prints the date in the format of YYYY-MM-DD. The good part is that the DateTime class is available straight ahead, and you don’t need to include a module as you do in Perl 5, for example.
$ perl6 -e'DateTime.now.yyyy-mm-dd.say'
2018-12-05
As you have already seen in the previous days of the calendar, chaining method calls is a typical Perl 6 thing. An opposite alternative would be to use say as a subroutine and use parentheses to mark method calls:
say(DateTime.now().yyyy-mm-dd());
This code also works; it is completely correct, but it looks heavy.
What you should also notice and tell your friends, is that in Perl 6, you can use dashes and apostrophes in identifiers.
Well, maybe using apostrophes is not a great idea, but hyphens are used very widely already in the source code of Perl 6. Just make sure you put spaces around minus operator in expressions to avoid any conflicts in parsing.
Exploring the sources or reading the documentation, you will find another method named in the same manner: hh-mm-ss. I bet you understand what it does.
> DateTime.now.hh-mm-ss.say
00:12:01
Notice that you will not find similar methods for different formats of the output, such as dd-mm-yy or hh-mm. Use formatter instead. It is not a method but an attribute defined in the Datish role. There is a default formatter in the DateTime class, but you may redefine it by providing the constructor with your own subroutine, for example:
DateTime.now(formatter => -> $dt {
sprintf '%02d.%02d.%04d',
$dt.day, $dt.month, $dt.year
}).say
A formatter here takes an anonymous subroutine (introduces by an arrow) with one argument $dt.
I hope this code prints the same date as our initial one-liner, as you most likely read the whole article within one day.
Nevertheless, see you tomorrow with a code that tests palindromes!
‘DateTime.now.Date.say’ will do.