in reply to Re^2: replace a digit with another digit
in thread replace a digit with another digit

heh. I had a capture and $1 in there orginally, and then to be 'clever' changed it to $& to save a couple characters :)

As far as the positive look-behind, y, it's not necessary -- just (since it's zero-width) saves having to reference a second capture in the replacement:
s/([a-z])([12])/ $1 . ($2 == 1 ? 2 : 1) /eig;
(i think the /i is less efficient, too.. too many different ways to write this one)

Replies are listed 'Best First'.
Re^4: replace a digit with another digit
by kevyt (Scribe) on Aug 18, 2005 at 13:45 UTC
    Thanks !!!! The 3 lines of code below work! The first char will always be a capital letter and the 2nd char will always be a number. Then I just need to change the number. So, I think the "." in line 3 will also be ok? I am curious how lines 2 and 3 below work.

    line 2 below ... it searches for a leter in lowercase. Then it joins what it changes in the next step.... If $2 is equal to 1 then change it to 2. If $2 is equal to 2, then it changes it to 1.

    Is the letter $0 and the number $1 ? I assume so.

    example input is "D1"
    # s/(?<=[a-zA-Z])([12])/ $1 == 1 ? 2 : 1 /eg; # s/([a-z])([12])/ $1 . ($2 == 1 ? 2 : 1) /eig; s/(.)([12])/ $1 . ($2 == 1 ? 2 : 1) /eig; this might work: s/([A-Z])([12])/ $1 . ($2 == 1 ? 2 : 1) /eig;
    THANKS TO EVERYONE !!!! Kevin
      line 2 below ... it searches for a leter in lowercase.
      Actually, it's any letter, upper OR lower, because of the /i modifier. Which makes this line 2 exactly equivalent to your 'this might work' line (let's call it line 4), so yes, line 4 works as well.

      Is the letter $0 and the number $1 ? I assume so.
      $0 returns the name of the program being run. $& returns the entire matched string. $1 and $2 return the first and second captured (patterns in parens) matches, so yes in lines 2, 3 and 4 the letter is $1 and the number is $2. Note the exception here is line 1, where the number is $1 -- this is because the look-behind (?<=foo) is zero-width and isn't considered part of the match.

      I am curious how lines 2 and 3 below work.
      Your description of line 2 (with the above case-correction) was accurate. The difference between line 2 and line 3 is that line 2 matches a single character from a character class (in this case only a letter) and that line 3 will match any character at all. For example, try them both against the strings "A1", "+1", "11", "A111" and compare the results.