in reply to parse a string

One way to do this is to use a regular expression:

my $string = "something, something, something, this"; my ($lastword) = $string =~ /\s(\S+)$/;
\s matches a space character. (\S+) matches one or more non-whitespace characters, and captures them. $ matches the end of line. Be sure to pay attention to whether your string has a newline at the end or not, and remove it or match for it as appropriate.

You could also use split(), but I'll leave that one for someone else.

Alan

Replies are listed 'Best First'.
(jeffa) 2Re: parse a string
by jeffa (Bishop) on May 03, 2002 at 15:13 UTC
    Here is the split way for Anony:
    my $string = "something, something, something, this"; my $lastword = ( split(/\s*,\s*/, $string) )[-1];
    First, you split on a comma, but since there is whitespace involved, i chose to use a regex that says "zero or more whitespace followed by a literal comma followed by zero or more whitespace". Since split returns a list, you can take advantage and add an index on the spot without using a temporary variable (well, sort of). In this case the index is -1, which is the last element.

    Of coures, this is not an efficient way to do it, but ... TIMTOWTDI! ;)

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)