Skip to content

Instantly share code, notes, and snippets.

@tommystanton
Last active July 10, 2019 02:37
Show Gist options
  • Save tommystanton/7b5213f1e222f825f0e73648d5540a7f to your computer and use it in GitHub Desktop.
Save tommystanton/7b5213f1e222f825f0e73648d5540a7f to your computer and use it in GitHub Desktop.
Perl 6 script to convert dates to ISO8601
#!/usr/bin/env perl6
use v6.d;
=begin DESCRIPTION
Given a newline-delimited file of mm/dd/yyyy, write a newline-delimited
file of yyyy-mm-dd.
=end DESCRIPTION
my $in = 'dates.txt'.IO;
my $out = 'dates_iso_8601.txt'.IO;
$out.spurt('');
for $in.lines {
m/
$<month> = (\d ** 1..2)
\/
$<day> = (\d ** 1..2)
\/
$<year> = (\d ** 4)
/;
my $date = Date.new($<year>, $<month>, $<day>);
$out.spurt("{ $date.yyyy-mm-dd }\n", :append);
}
@lizmat
Copy link

lizmat commented Jun 16, 2019

You can easily overwrite STDOUT to your own handle, which will allow you to use say, so you don't have to interpolate into a string. Also, if you're using spurt(... :append), you're opening and closing an OS handle for every spurt. Which is sorta sub-optimal :-)

my $in = 'dates.txt'.IO;
my $*OUT = open('dates_iso_8601.txt',:w);

for $in.lines {
    m/
        $<month> = (\d ** 1..2)
        \/
        $<day> = (\d ** 1..2)
        \/
        $<year> = (\d ** 4)
    /;

    say Date.new($<year>, $<month>, $<day>).yyyy-mm-dd;
}   
$*OUT.close;

Note, unlike Perl 5, handles aren't automatically closed when they go out of scope (but of course, will be by the OS on program exit). So it is better to do this yourself, generally. Or use a LEAVE phaser like:

LEAVE $*OUT.close;

@tommystanton
Copy link
Author

Thank you so much for the code review, @lizmat! I've seen the $*OUT trick but have yet to try it (and didn't think to in this context), so I will check it out. 😎

Thank you especially for all of your hard work on the Perl 6 project; I am a huge fan and I am extremely grateful for how the language is coming along.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment