Perl: Finding the last word of a string

Articles may may have files attached at the end of the post

This code sample will show how to find the last word in a string. A word being composed of letters and numbers only.

  1. #!/usr/bin/env perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. my @strings = ("This is a string ending with a dot . ", "£{}*(^", "£&nospace[]");
  7.  
  8. foreach (@strings){
  9.   my $lastword = undef;
  10.   print "Original string is: **".$_."**\n";
  11.   if ($_ =~ m/(\w+)\s*\W*\s*$/x){
  12.     $lastword = $1;
  13.   }
  14.   print "Last word is: **".(defined($lastword)? $lastword: "undefined")."**\n\n";
  15. }

Will output:

$ ./lastword.pl 
Original string is: **This is a string ending with a dot . **
Last word is: **dot**

Original string is: **£{}*(^**
Last word is: **undefined**

Original string is: **£&nospace[]**
Last word is: **nospace**