in reply to Replace the last letter

#!/usr/bin/perl use strict; use warnings; my $tofind="s"; my $replacement="X"; my $variable="snaskes"; print "Before: $variable\n"; $variable =~ s/$tofind[^$tofind]*$/$replacement/; # OR # $variable =~ s/$tofind(?![$tofind])$/$replacement/; print "After: $variable\n";

Replies are listed 'Best First'.
Re^2: Replace the last letter
by hv (Prior) on Oct 08, 2004 at 15:10 UTC

    The main version does the right thing, but the alternative doesn't - negative lookahead will look for something immediately following, so:

    $variable =~ s/$tofind(?![$tofind])$/$replacement/;
    means "find the letter, not followed by the letter again, but followed by the end anchor". I think you want instead:
    $variable =~ s/$tofind(?!.*$tofind)/$replacement/;
    ie "find the letter, not followed by (zero or more characters and) the letter again".

    Also, the [$tofind] character class is the same as $tofind itself when it refers to a single letter, but doesn't do the right thing if $tofind is something more complex.

    Hugo