Editorial for Lyndon's Golf Contest 1 P6 - Alphanumeric Perl
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
27 bytes
Let's first figure out how to print just one DMOJ
. To do this, we'll need a way to represent a string without quotes ('
or "
). It turns out that Perl has a special operator called q/STRING/
, which lets us define a string within any delimiter (the example uses /
, but this could be any character). From this, we can use print q qDMOJq
to output DMOJ
. Note the space between the first and second q
, to disambiguate from a similar operator called qq/STRING/
.
Consider if the problem had asked us to print DMOJ
times on a single line. We could then use Perl's repetition operator x
to repeat the string times:
print q qDMOJq x10
However, what we really want is to print is "DMOJ\n"
times, so we'll need to a way of appending a newline to a string. The shortest way to represent a newline is through version strings, which allows us to construct a string from its Unicode codepoints. The ASCII value for \n
is , so a newline literal can be created with v10
. To append the two parts together, we will use the powerful feature of regular expressions. The idea is to take v10
, and replace the beginning of it with DMOJ
, which can be done in Perl via v10=~s//DMOJ/r
, where s///r
is Perl's syntax for substituting a string in-place. As with the q
operator, the /
represents any delimiter, so we can replace it with any lowercase letter: v10=~s ssDMOJsr
.
Unfortunately, the =~
still remains, so how do we get rid of it? We need it to tell the regex which string to replace, but we can also do this through Perl's topic variable, $_
. If $_
is set, the regex will implicitly match with the string in $_
without needing =~
. In other words, s///r
is equivalent to $_=~s///r
. Given this, all that's left to do is set $_
to DMOJ
. We can't do this directly, but Perl's for
loop happens to store its current element in $_
. This lets us do the following: s///r for v10
. And for the full solution, we have:
print s ssDMOJsr x10for v10
Comments