diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2020-10-22 21:14:20 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-10-22 21:14:20 +0100 |
| commit | 159da47e041139fbd0382559dbdb11e129928f75 (patch) | |
| tree | fed3f4f0f45866ea03258e2e7db3e4251bb9dc12 | |
| parent | 9581cfd50faaa15f99a5cbdaf0f0c71d16f4282e (diff) | |
| parent | e5727d14b52a40df0de1178af54981474b1c1402 (diff) | |
| download | perlweeklychallenge-club-159da47e041139fbd0382559dbdb11e129928f75.tar.gz perlweeklychallenge-club-159da47e041139fbd0382559dbdb11e129928f75.tar.bz2 perlweeklychallenge-club-159da47e041139fbd0382559dbdb11e129928f75.zip | |
Merge pull request #2595 from yewtc/master
Add challenge 038 perl 1
| -rw-r--r-- | challenge-083/steve-rogerson/perl/ch-1.pl | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/challenge-083/steve-rogerson/perl/ch-1.pl b/challenge-083/steve-rogerson/perl/ch-1.pl new file mode 100644 index 0000000000..d25dba64cb --- /dev/null +++ b/challenge-083/steve-rogerson/perl/ch-1.pl @@ -0,0 +1,54 @@ +use strict; +use warnings; +use utf8; +use 5.028; +use feature qw(signatures); +no warnings 'experimental::signatures'; +## no critic (Subroutines::ProhibitSubroutinePrototypes) +# +# "You are given a string $S with 3 or more words. +# Write a script to find the length of the string +# except the first and last words ignoring whitespace." +# +# A string ok, so what's a word? In the land of perl regex , a word character is alphanumeric + _. +# So .. if there are three words we drop the outside two - then strip any white space and return the result. + +my @strings = ( + "Two words", + "One Two Three", + "pre/mid/post", + "pre/ mid/post", + "pre/\x{A0}mid/post", # non-breaking space just for fun. + "pre/ mid mid2/post", + "pre/ mid mid2/post", + "pre/ mid\n mid2/post", +); + +for my $string (@strings) { + my $len = find_middle_string_length($string); + if ( !$len ) { + say "No middle "; + next; + } + say "The middle bit length, ignoring white space is " . $len; +} + +sub find_middle_string_length($string) { + my ($middle) = $string =~ / + \A\W* # skip leading junk before first word. + \w+ # The first word. + \W+ # at least one not word char + (.*) # everything else (inc c-r with s modifier) + \W+ # at least one not word char + \w+ # the final word + \W* # optional junk + \z /msx; + + # end of string. Match on multi-line and have c-r included in ",*" match + + return 0 if !$middle; + + # Strip out white space. + $middle =~ s/\s//mgx; + return length($middle); +} |
