The weekly challenge 250 - Task 2: Alphanumeric String Value

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-250/#TASK2
 3 #
 4 # Task 2: Alphanumeric String Value
 5 # =================================
 6 #
 7 # You are given an array of alphanumeric strings.
 8 #
 9 # Write a script to return the maximum value of alphanumeric string in the
10 # given array.
11 #
12 # The value of alphanumeric string can be defined as
13 #
14 # a) The numeric representation of the string in base 10 if it is made up of
15 #    digits only.
16 # b) otherwise the length of the string
17 #
18 #
19 ## Example 1
20 ##
21 ## Input: @alphanumstr = ("perl", "2", "000", "python", "r4ku")
22 ## Output: 6
23 ##
24 ## "perl" consists of letters only so the value is 4.
25 ## "2" is digits only so the value is 2.
26 ## "000" is digits only so the value is 0.
27 ## "python" consits of letters so the value is 6.
28 ## "r4ku" consists of letters and digits so the value is 4.
29 #
30 ## Example 2
31 ##
32 ## Input: @alphanumstr = ("001", "1", "000", "0001")
33 ## Output: 1
34 #
35 ############################################################
36 ##
37 ## discussion
38 ##
39 ############################################################
40 #
41 # Try to match each string against a non-digit character. If that succeeds (or
42 # the length is 0), use the length. If it doesn't, convert the string to an
43 # integer.
44 
45 use strict;
46 use warnings;
47 
48 alphanumeric_string_value("perl", "2", "000", "python", "r4ku");
49 alphanumeric_string_value("001", "1", "000", "0001");
50 
51 sub alphanumeric_string_value {
52    my @alphanumstr = @_;
53    print "Input: (" . join(", ", @alphanumstr) . ")\n";
54    my $max = 0;
55    foreach my $string (@alphanumstr) {
56       # We skip the case where length($string) == 0, as that's the
57       # default for $max anyway
58       if(length($string) != 0) {
59          if($string =~ m/[^\d]/) {
60             $max = length($string) if length($string) > $max;
61          } else {
62             $max = int($string) if int($string) > $max;
63          }
64       }
65    }
66    print "Output: $max\n";
67 }