Perl Weekly Challenge: Week 230

A relaxing week this time. I was able to do both challenges in half an hour.

Challenge 1:

Separate Digits

You are given an array of positive integers.

Write a script to separate the given array into single digits.

Example 1
Input: @ints = (1, 34, 5, 6)
Output: (1, 3, 4, 5, 6)
Example 2
Input: @ints = (1, 24, 51, 60)
Output: (1, 2, 4, 5, 1, 6, 0)

All we need to do to solve this in Raku is to iterate over each command-line argument with .map(), split each argument into digits with.comb() plus the | operator for "flattening" the result to get digits rather than a list of digits and join the digits together again with .join(). The rest of this one-liner is just for getting the output into the same format as in the examples.

say q{(},@*ARGS.map({|.comb}).join(q{, }),q{)}

(Full code on Github.)

We can do the same thing in Perl. Remarkably the Perl version is actually shorter than Raku because we don't need |; Perl flattens by default.

say q{(},(join q{, },map{split//}@ARGV),q{)}

(Full code on Github.)

Challenge 2:

Count Words

You are given an array of words made up of alphabetic characters and a prefix.

Write a script to return the count of words that starts with the given prefix.

Example 1
Input: @words  = ("pay", "attention", "practice", "attend")
       $prefix = "at"
Ouput: 2

Two words "attention" and "attend" starts with the given prefix "at".
Example 2
Input: @words  = ("janet", "julia", "java", "javascript")
       $prefix = "ja"
Ouput: 3

Three words "janet", "java" and "javascript" starts with the given prefix "ja".

Also a one-liner. We take out the first command-line argument to use as the prefix (assigned to $p for brevity.) Then we search through the rest of the arguments with .grep() using a regular expression to find ones that start with the prefix. Once we have those, we count them up with .elems() and print the result with .say().

my$p=@*ARGS.shift;@*ARGS.grep({/^$p/}).elems.say

(Full code on Github.)

The Perl version works the same way modulo the usual differences in syntax. Once again it is shorter than the Raku version--this time remarkably so. Overall I prefer the consistency of Raku's syntax for real world applications.

$p=shift;say scalar grep{/^$p/}@ARGV

(Full code on Github.)