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,


In reply to Re: need help with explaining the output by Athanasius
in thread need help with explaining the output by perlynewby

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.