Even if you were more comfortable with regular expressions, split would have been a good choice for this problem.

However, getting comfortable with regular expressions will open up a world of programming possibilities to you. It is worth investing the effort, even if it feels intimidating at first. One way to build confidence is to see problems you already understand well reworked into regular expressions, so here it is:

my ($lastWord) = $rec =~ /(\S+)$/; print "$lastWord\n"; #prints 96 #or $rec =~ /(\S+)$/; my $lastWord = $1; print "$lastWord\n"; #also prints 96

And we even could have combined your trailing space tripping code with the regular expression as well. This also would have worked: my ($lastWord) = $rec =~ /(\S+)\s*$/. \s* is like \s+ except that it matches zero or more spaces, rather than one or more. That is \s+ is equivalent to \s\s*.

For more information and some further examples, see perlretut.

Best, beth


In reply to Re: Non-regex Methods of Extracting the Last Field from a Record by ELISHEVA
in thread Non-regex Methods of Extracting the Last Field from a Record by ozboomer

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.