Movie file reader

Last night I finally got to see The Martian. It was a fun movie, and it seems much of the science was solid. One thing that filmmakers still like to do is have computers spit out messages one-character-at-a-time as if they were arriving like telegrams. If you would like to read a file like this, I present the movie-file-reader. First, my very long-hand version:

#!/usr/bin/env perl6

sub MAIN (Str $file) {
for $file.IO.lines(:chomp(False)) -> $line {
for $line.comb -> $letter {
print $letter;
my $pause = do given $letter {
when /<[.!?]>/ { .50 }
when /<[,;]>/ { .20 }
default { .05 }
}
sleep $pause;
}
}
}

So I'm reading the given $file line-by-line, telling Perl not to "chomp" each line (remove the newline for whatever value constitutes that, which, BTW, you can set with "nl-in"). I "print" the letter, not "put" because I don't want a newline after it. Then I need to pause with the "sleep" because computers move way faster than the human eye. To figure out how long to sleep, I want to inspect the character for punctuation that either ends a sentence or introduces a pause. I use "<[]>" to create a character class that includes a period, exclamation point, and question mark or one that includes a comma or semi-colon. The "do given" lets me return the value of the "given" statement, effectively turning it into a "given" operator.

I always bounce my ideas off #perl6 on IRC, and Zoffix suggested this much shorter version:

#!/usr/bin/env perl6

sub MAIN (Str $file) {
for $file.IO.comb {
.print;
sleep /<[.!?]>/ ?? .30
!! /<[,;]>/ ?? .10
!! .05;
}
}

Here we're reading the file character-by-character into the default "$_" topic variable upon which we can call the ".print" method. Then we sleep (perchance to dream) using a stacked ternary operator to find how long. Much shorter, but more cryptic to the uninitiated. I like both versions because 1) they both work 2) they allow the programmer varying levels of expressiveness and efficiency.

1 Comment

I like this post! I think in the case of The Martian, the letters were indeed arriving from a long voyage from the earth (though to be fair, probably not one letter at time).

Leave a comment

About Ken Youens-Clark

user-pic I work for Dr. Bonnie Hurwitz at the University of Arizona where I use Perl quite a bit in bioinformatics and metagenomics. I am also trying to write a book at https://www.gitbook.com/book/kyclark/metagenomics/details. Comments welcome.