Perl Weekly Challenge: Week 240

Both the tasks were very easy this week. In both Perl and Raku, they can be expressed as one-liners and in fact it took me longer to write this blog post than it did to write them!

Challenge 1:

Acronym

You are given an array of strings and a check string.

Write a script to find out if the check string is the acronym of the words in the given array.

Example 1
Input: @str = ("Perl", "Python", "Pascal")
    $chk = "ppp"
Output: true
Example 2
Input: @str = ("Perl", "Raku")
    $chk = "rp"
Output: false
Example 3
Input: @str = ("Oracle", "Awk", "C")
    $chk = "oac"
Output: true

I did Perl first this week.

shift() in this case will remove and return the first command-line argument which we shall be using as the check string. For the rest of the arguments (in @ARGV) we use map() to iterate over them, picking out the first character of each argument with substr() and converting it to lower case with lc(). These characters are then concatenated with join() and the result is compared to the check string. If the two are equal, 'true' is printed out otherwise 'false'.

say shift eq (join q{},map{lc substr $_,0,1}@ARGV)?"true":"false"

(Full code on Github.)

This is the Raku version. Instead of shift()ing off the first argument, I referred to it directly and used an array slice for the rest of the arguments. In Raku there is no need to explicitly print True or False as they are built-in to the language.

say @*ARGS[0] eq @*ARGS[1..*].map({$_.substr(0,1).lc}).join(q{})

(Full code on Github.)

Challenge 2:

Build Array

You are given an array of integers.

Write a script to create an array such that new[i] = old[old[i]] where 0 <= i < new.length.

Example 1
Input: @int = (0, 2, 1, 5, 3, 4)
Output: (0, 1, 2, 4, 5, 3)
Example 2
Input: @int = (5, 0, 1, 2, 3, 4)
Output: (4, 5, 0, 1, 2, 3)

Perl first again.

Once more, map() is used to transform the input. Each command-line argument is treated as an index and the corresponding argument is added to the results. And that's it. The rest of the code is just to print the results in a nice way.

say q{(},(join q{, },map{@ARGV[$_]}@ARGV),q{)}

(Full code on Github.)

And this is the Raku version.

say q{(},@*ARGS.map({@*ARGS[$_]}).join(q{, }),q{)}

(Full code on Github.)