rightfield has asked for the wisdom of the Perl Monks concerning the following question:

Hi experts, I have a string in $frameDesc that looks like 'Standard 6' and I want to grab the '6' from the end. I have the condition working but the '6' is not where I expected it. Could someone tell me how to print the digit(s) at the end of a string please. Thank you.
if ($frameDesc =~ /\d+$/ ) { print FH "FTP ". $+ . "\n"; } else { print FH "FTP 0\n"; }

Replies are listed 'Best First'.
Re: where is /\d+$/ result??
by ikegami (Patriarch) on May 04, 2008 at 01:02 UTC

    $+: The text matched by the last bracket of the last successful search pattern.

    I don't see any parens in there.

    if ($frameDesc =~ /(\d+)$/ ) { print FH "FTP $1\n"; } else { print FH "FTP 0\n"; }
    or
    my $num = $frameDesc =~ /(\d+)$/ ? $1 : 0; print FH "FTP $num\n";
      Thank you ikegami for both solutions.
Re: where is /\d+$/ result??
by GrandFather (Saint) on May 04, 2008 at 01:12 UTC

    You may be interested in rummaging through perlretut and perlre.


    Perl is environmentally friendly - it saves trees
Re: where is /\d+$/ result??
by apl (Monsignor) on May 04, 2008 at 01:12 UTC
    As this shows, $+ is the position of the match, not the value of the match. You need to use parentheses to indicate what you want to preserve, with $1 indicating the value of the first match. So your code should look like:
    if ($frameDesc =~ /(\d+)$/ ) { print FH "FTP $1\n"; } else { print FH "FTP 0\n"; }
    Or, if you were interested in Perl Golf, you might try
    my $value = ($frameDesc =~ /(\d+)$/ ) ? $1 : 0; print FH "FTP $value\n";

    If you had two sets of parentheses in your regex and you wanted to manipulate the second value, you'd specify $2, etc.

    Warning: the code is untested.

      See: Mastering Regular Expressions, 2nd ed., ISBN: 0-596-00289-0, Friedl, pp300-301.

      "$+   This is a copy of the highest numbered $1, $2, etc. explicitly set during the match."

      The "this" (perlvar) you cite phrases it this way:

      "$+
      The text matched by the last bracket of the last successful search pattern. This is useful if you don't know which one of a set of alternative patterns matched."

      Whereas perldoc perlretut states this re @+ and @-:

      In addition to what was matched, Perl 5.6.0 also provides the positions of what was matched with the "@-" and "@+" arrays.

      As [perlvar] shows, $+ is the position of the match, not the value of the match.

      You appear to be confusing $+ with @+.