perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 360 - Task 2: Word Sorter

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-360/#TASK2
 3 #
 4 # Task 2: Word Sorter
 5 # ===================
 6 #
 7 # You are give a sentence.
 8 #
 9 # Write a script to order words in the given sentence alphabetically but keeps
10 # the words themselves unchanged.
11 #
12 ## Example 1
13 ##
14 ## Input: $str = "The quick brown fox"
15 ## Output: "brown fox quick The"
16 #
17 #
18 ## Example 2
19 ##
20 ## Input: $str = "Hello    World!   How   are you?"
21 ## Output: "are Hello How World! you?"
22 #
23 #
24 ## Example 3
25 ##
26 ## Input: $str = "Hello"
27 ## Output: "Hello"
28 #
29 #
30 ## Example 4
31 ##
32 ## Input: $str = "Hello, World! How are you?"
33 ## Output: "are Hello, How World! you?"
34 #
35 #
36 ## Example 5
37 ##
38 ## Input: $str = "I have 2 apples and 3 bananas!"
39 ## Output: "2 3 and apples bananas! have I"
40 #
41 ############################################################
42 ##
43 ## discussion
44 ##
45 ############################################################
46 #
47 # We split $str into its individual words and put it back
48 # together in the properly sorted way: sorted alphabetically,
49 # but ignoring case while doing that.
50 
51 use v5.36;
52 
53 word_sorter("The quick brown fox");
54 word_sorter("Hello    World!   How   are you?");
55 word_sorter("Hello");
56 word_sorter("Hello, World! How are you?");
57 word_sorter("I have 2 apples and 3 bananas!");
58 
59 sub word_sorter($str) {
60     say "Input: \"$str\"";
61     my @words = split /\s+/, $str;
62     say "Output: \"" . join(" ", sort { lc($a) cmp lc($b) } @words) . "\"";
63 }