Perl Weekly Challenge: Week 1

Unfortunately I don't get to use Perl that much anymore so when Mohammad Anwar announced the Perl Weekly Challenge I thought it would be fun to take part and keep the old skills sharp. Every week there will be two challenges. Answers can be given in Perl 5 or Perl 6 and I have decided I shall try to do both.

The first challenge is:

Write a script to replace the character 'e' with 'E' in the string 'Perl Weekly Challenge' Also print the number of times the character 'e' is found in the string.

We can do this as a one liner in Perl.

perl -E '$str = "Perl Weekly Challenge"; $count = $str =~ s/e/E/g; say "$str has $count letter E'\''s in it.";'

(Full code on Github.)

Using the -E command switch instead of -e allows us to use the say command which saves you having to add an \n to the end of a string when you print it.

In scalar context, s// returns the number of substitutions.

I had to do that weird '\'' thing to get an apostrophe not because of Perl but because the shell (Bash on Linux in my case) intercepts it.

The Perl6 version is also fairly easy:

perl6 -e 'my $str = "Perl Weekly Challenge"; my $count = ($str ~~ s:g/e/E/).elems; say "$str has $count letter e'\''s in it.";'

(Full code on Github.)

Perl6 uses ~~ instead of =~ to bind the results of a regex to a variable.

The precedence of operators is a little different so we have to put the substitution in parentheses. Also an array of substitutions is returned instead of a scalar count so we have to use the .elems method to count the length of this array.

The second challenge is:

Write a one-liner to solve the Fizzbuzz problem and print the numbers 1 through 20. However, any number divisible by 3 should be replaced by the word 'fizz' and any divisble by 5 by the word 'buzz'. Those numbers that are divisible by 3 and 5 become 'fizzbuzz'.

My favorite way of doing fizzbuzz in C-like languages is with the ternary operator like this.

perl -E 'for (1 .. 20) { say $_ % 15 ? $_ % 5 ? $_ % 3 ? $_ : "fizz" : "buzz" : "fizzbuzz" } ;'

(Full code on Github.)

My Perl6 version is the same except ? and : have been replaced by ?? and !!.

perl6 -e 'for 1 .. 20 { say $_ % 15 ?? $_ % 5 ?? $_ % 3 ?? $_ !! "fizz" !! "buzz" !! "fizzbuzz" };

(Full code on Github.)