RabbitFarm

2019-04-02

Perl Weekly Challenge 001

I just learned about https://perlweeklychallenge.org/ which posts a small coding challenge each week. They seem to have started up 25 March 2019 so, as of this writing, there have been two challenges posted. Below is my take on each of the two parts to challenge 001. The problem statements are short and are included in the first comment of the code. The code blocks shown link to GitHub Gists.

Part 1

The problem statement seems like a clear use for tr. tr will perform the substitution on the string and return the number of substitutions made. This can be done in one line, of course, and would look like: 

    my $number=$challenge_string=~tr/e/E/;

It's easy to argue that is not the most easily read line of code. I opted to perform the substitution in a do block. The return value from the block is the value returned from the last (in this case only) statement and so it is more clear just what is being performed and what is being assigned to $number.


Part 2

This is a classic problem and since I had blocks on my mind from part one I decided to use the less common redo to perform the looping. redo will cause the block it is enclosed in to be performed again, provided a given condition is true. The use of until is a bit gratuitous but using it here in this way, I'd argue, makes the code read, as an English expression, very clearly: the block will repeat until $i exceeds 20. Finally, I decided to use a Perl's switch statements which have a given/when syntax. Switch statements in Perl have a complicated history. The original implementation had bugs and it's use has been deemed experimental. This seems mostly due to its use of the so-called smart match operator ~~. This code doesn't rely on the ~~ operator's sometimes confusing behavior so it's use here doesn't relate to any of the controversy.



posted at: 16:04 by: Adam Russell | path: /perl | permanent link to this entry