The Weekly Challenge - 278


TASK #1: Sort String
You are given a shuffle string, $str. Write a script to return the sorted string.

A string is shuffled by appending word position to each word.

#!/usr/bin/perl
use strict;
use warnings;

sub sort_string {

    return (join(" ", map { $_ =~ s/\d+//gr } 
                      sort( { substr($a, -1, 1) <=> substr($b, -1, 1) } 
                      split(/\s+/, $_[0]) ))) ;
};

# TESTS

my $str;

# Example 1
$str = "and2 Raku3 cousins5 Perl1 are4";
print(sort_string($str), "\n"); # Output: "Perl and Raku are cousins"

# Example 2
$str = "guest6 Python1 most4 the3 popular5 is2 language7";
print(sort_string($str), "\n"); # Output: "Python is the most popular guest language"

# Example 3
$str = "Challenge3 The1 Weekly2";
print(sort_string($str), "\n"); # Output: "The Weekly Challenge"

TASK #2: Reverse Word
You are given a word, $word and a character, $char.

Write a script to replace the substring up to and including $char with its characters sorted alphabetically. If the $char doesn’t exist then DON'T do anything.
#!/usr/bin/perl
use strict;
use warnings;

sub reverse_word {
    
    my $index = index($_[0], $_[1]);

    return(join("", sort( split(//, substr($_[0], 0, $index + 1)) ), 
                    substr($_[0], $index + 1), "\n"));
}

# TESTS

my $str;
my $char;

# Example 1
$str = "challenge";
$char = "e";
print(reverse_word($str, $char), "\n"); # Output: "acehllnge"

# Example 2
$str = "programming";
$char = "a";
print(reverse_word($str, $char), "\n"); # Output: "agoprrmming"

# Example 3
$str = "champion";
$char = "b";
print(reverse_word($str, $char), "\n"); # Output: "champion"