Perl Weekly Challenge 250: Alphanumeric String Value

These are some answers to the Week 250, Task 2, of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Task 1: Alphanumeric String Value

You are given an array of alphanumeric strings.

Write a script to return the maximum value of alphanumeric string in the given array.

The value of alphanumeric string can be defined as

a) The numeric representation of the string in base 10 if it is made up of digits only. b) otherwise the length of the string

Example 1

Input: @alphanumstr = ("perl", "2", "000", "python", "r4ku")
Output: 6

"perl" consists of letters only so the value is 4.
"2" is digits only so the value is 2.
"000" is digits only so the value is 0.
"python" consits of letters so the value is 6.
"r4ku" consists of letters and digits so the value is 4.

Example 2

Input: @alphanumstr = ("001", "1", "000", "0001")
Output: 1

Alphanumeric String Value in Raku

We transform in input array into an array of numerical values where strings containing digits only are transformed into their numerical values, and other strings replaced by their length, and finally return the maximum value.

sub alphanum-string (@in) {
    my @out = map {  /^\d+$/ ?? 0 + $_ !! $_.chars }, @in;
    return max @out;

for ( "perl", "2", "000", "python", "r4ku"),  
    ("001", "1", "000", "0001") -> @test {
    say alphanum-string @test;

This program displays the following output:

$ raku ./alphanum-string.raku

Alphanumeric String Value in Perl

This is a port to Perl of the above Raku program. Please refer to the previous section if you need any explanations.

use strict;
use warnings;
use feature 'say';

sub alphanum_string {
    my @out = map {  /^\d+$/ ? 0 + $_ : length $_ } @_;
    return (sort { $a <=> $b } @out)[-1];

for my $test ( ["perl", "2", "000", "python", "r4ku"],
    ["001", "1", "000", "0001"]) {
    say alphanum_string @$test;

This program displays the following output:

$ perl ./

Wrapping up

Happy new year to everyone. The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check and make sure you answer the challenge before 23:59 BST (British summer time) on January 14, 2024. And, please, also spread the word about the Perl Weekly Challenge if you can.

Leave a comment

About laurent_r

user-pic I am the author of the "Think Perl 6" book (O'Reilly, 2017) and I blog about the Perl 5 and Raku programming languages.