TASK #1: Largest Number
You are given a list of positive integers, @ints.
Write a script to arrange all the elements in the given list such that they form the largest number and return it.
#!/usr/bin/perl use strict; use warnings; sub max_concatenated_value { my ($aref) = @_; die "Expected an array reference\n" unless ref($aref) eq 'ARRAY'; die "Empty array\n" unless @$aref; # If a function changes elements, make a local copy. my @arr = @$aref; for (my $i = 0; $i < @arr; $i++) { die "Undefined value encountered\n" unless defined $arr[$i]; die "Invalid value '$arr[$i]' (only non-negative integers allowed)\n" unless $arr[$i] =~ /^\d+$/;# Strip leading zeros, keep single zero $arr[$i] =~ s/^0+(?=\d)//; }# Sort using Perl's special global sort variables $a and $b: # for each comparison, order elements so "b.a" > "a.b", # then join to form the maximum concatenated value. my $result = join '', sort { $b.$a cmp $a.$b } @arr;# It collapses a string made of only zeros into a single "0". # @arr = ("0", "00", "000"); gives $result = "000"; # Now: $result = "0"; $result =~ s/^0+$/0/; return $result; } # Tests my @ints; @ints = (20, 3); printf "%d\n",max_concatenated_value(\@ints);# Output: 320 @ints = (34, 3); printf "%d\n",max_concatenated_value(\@ints);# Output: 343 @ints = (3, 30, 34, 5, 9); printf "%d\n",max_concatenated_value(\@ints);# Output: 9534330