Octal Representation

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

Challenge 1 this week is an easy one:

Write a script to print decimal number 0 to 50 in [the] Octal Number System.

Perl and Raku

We can solve this with the following polyglot (runs in both languages at once):

printf "Decimal %2d = Octal %2o\n", $_, $_ for 0..50;

Still, in Raku, we can do the following:

say (0..50).fmt('Decimal %1$2d = Octal %2o', "\n");

We are able to do this by re-using the argument to fmt. That fmt/printf syntax doesn’t tend to get used often, but it’s been around for a very long time, and works in many other languages, including Perl:

printf 'Decimal %1$2d = Octal %1$2o'."\n", $_ for 0..50;

We are able to use the first argument twice thanks to the 1$ between the % and the type (d or o in this case). n$ is a POSIX extension that tells printf to use the nth argument, instead of whatever might be next in the list.

GitHub solutions: Perl, Raku.

Leave a Reply

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