in reply to Variable assignment confusion

The 1 is the return value from the successful match. Try:
my $new_retid = ($retid =~ /_\d{3}\z/ ? $retid : $retid . "_001");

Replies are listed 'Best First'.
Re: Re: Variable assignment confusion
by Roy Johnson (Monsignor) on Dec 15, 2003 at 18:53 UTC
    Which is (factoring out the common prefix):
    my $new_retid = $retid . ($retid =~ /_\d{3}\z/ ? '' : '_001');

    The PerlMonk tr/// Advocate
Re: Re: Variable assignment confusion
by sweetblood (Prior) on Dec 15, 2003 at 19:05 UTC
    This is no doubt what I was thinking about. Thanks! One question. Why a \z instead of $ at the end of the expression? Don't get me wrong, I'm sure your correct I just don't understand.

    Thanks to All!

      Please don't assume that someone else is right just because they are more experienced than you; always try (as you have done :) to get an explanation. Cargo cultism often stems from unquestioningly assuming that unusually-written code is that way for a reason.

      As to your inquiry, '\z' matches the very end of the string; whereas '$' matches the end, or just before a newline at the end of a string.
      This doesn't make any difference in your case; so I'd use '$' to avoid confusion.

      If you're curious; '\z' becomes much more useful when you switch on the '/m' (multi-line) flag on a regex to allow '$' to match before any newlines in the string. Have a look at perldoc perlre or Mastering Regular Expressions for more details.

        This doesn't make any difference in your case; so I'd use '$' to avoid confusion.
        IMO, using $ causes confusion.
      • To those who know the difference between \z and $, it confuses what the code does
      • To those who don't, it perpetuates their confusion.

        Note that \Z (capital) is equivalent to (?-m:$) (i.e. does what $ does not under //m) even when //m is on. \z (lowercase) always is just the end of the string.

      With $, it would match either "9999_999\n" or "9999_999", which is not what your original post requested.