perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 331 - Task 1: Last Word

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-331/#TASK1
 3 #
 4 # Task 1: Last Word
 5 # =================
 6 #
 7 # You are given a string.
 8 #
 9 # Write a script to find the length of last word in the given string.
10 #
11 ## Example 1
12 ##
13 ## Input: $str = "The Weekly Challenge"
14 ## Output: 9
15 #
16 #
17 ## Example 2
18 ##
19 ## Input: $str = "   Hello   World    "
20 ## Output: 5
21 #
22 #
23 ## Example 3
24 ##
25 ## Input: $str = "Let's begin the fun"
26 ## Output: 3
27 #
28 ############################################################
29 ##
30 ## discussion
31 ##
32 ############################################################
33 #
34 # We begin by removing trailing whitespace, then we split the
35 # string into its words, of which we then calculate the length
36 # of the last one.
37 
38 use v5.36;
39 
40 last_word("The Weekly Challenge");
41 last_word("   Hello   World    ");
42 last_word("Let's begin the fun");
43 
44 sub last_word($str) {
45     say "Input: \"$str\"";
46     $str =~ s/ +$//;
47     my @words = split/\s+/,$str;
48     say "Output: " . length($words[-1]);
49 }
50