in reply to need help with explaining the output
Hello perlynewby,
First off, it’s good that you use strict; but you should always use warnings; as well.
Now, in this regex:
/^(.*)+([^ ]+)$/
the characters * and + are both quantifiers, meaning they tell the regex engine how many of the preceding entity it should try to match. * means zero or more, and + means one or more. So the construct (.*)+ means: match zero or more non-newline characters zero or more times, and do this one or more times. Which doesn’t make a lot of sense. See “Quantifiers” in perlre#Regular-Expressions and consider carefully which quantifier you need.
As stevieb has explained, these quantifiers are greedy, meaning the regex engine will try to match as many characters as possible and stop looking after the longest successful match. To make the quantifiers non-greedy, append a ?:
use strict; use warnings; my @original_names = ( 'Fred Flintstone', 'Leonardo da Vinci ', 'Raffaello da Urbino', ); my @cognome = last_name_first(@original_names); print join(';', @cognome); sub last_name_first { my @names = @_; for (@names) { s/\s+$//; s/^(.*?)(\S+)$/$2, $1/; s/\s+$//; } return @names; }
Output:
17:14 >perl 1308_SoPW.pl Flintstone, Fred;Vinci, Leonardo da;Urbino, Raffaello da 17:14 >
Note that the above script also removes trailing whitespace from the last and first names. In the former case, the whitespace might be there; in the latter case, it is certain to be. The character class \S matches any non-whitespace character.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: need help with explaining the output
by perlynewby (Scribe) on Jul 20, 2015 at 22:03 UTC |