in reply to string translation

A tip for next time; those who post code get more thorough responses.

It's not really a translation/transliteration problem. tr/// passes through a string a character at a time, transliterating based upon your tr/source-class/dest-class/. For example, tr/A-Z/a-z/ lowercases a string, because it goes through each char in a string, and if it is in the class A-Z, it gets translated to its companion in the class a-z.

What you want is a substitution: s///

$string = 'polar bear'; $string = uc $string; ## make all-uppercase $string =~ s/.{3}$/lc $&/e; ## lowercase 3 chars at end

At the end of that block, $string will contain 'POLAR Bear'.

That regex is a little confusing, but it's actually quite simple. The .{3} says "match any set of exactly 3 chars", and the $ says "at the end of the string". As for the second half, lc $& calls the lc function on the variable $&, which will contain the matched chars -- in this case, the last three of the string. The e on the end tells the substitution to eval the second part, otherwise it would replace the last three chars with 'lc ' and the chars themselves: 'POLAR BEAR' would become 'POLAR Blc EAR'.

I assumed you meant "uppercase all but the last three chars", which is what your examples seemed to say. If you meant "uppercase the first N, lowercase the last 3, and leave the rest alone, you could do this:

$string = 'polar BEAR'; $N = 4; $string =~ s/^.{$N}/uc $&/e; ## uppercase $N chars at start $string =~ s/.{3}$/lc $&/e; ## lowercase 3 chars at end

This would result in 'POLAr Bear'. The regex works similar to the one above, but ^ says "at the beginning of the string".

Anima Legato
.oO all things connect through the motion of the mind

Replies are listed 'Best First'.
Re^2: string translation
by shenme (Priest) on Dec 28, 2004 at 23:44 UTC
    And to do it all in one step:
    $string =~ s/^(.*)(.{3})$/\U\1\L\2/;
    See perlop for the \U and \L escapes.

    Wondering what would happen if the string was three characters or less led me to this, which might be something the AM might consider.

    $string =~ s/^(.*?)(.{1,3})$/\U$1\L$2/;