Perl FAQ 4.23: How can I change the first N letters of a string?

Perl FAQ 4.23

How can I change the first N letters of a string?

Remember that the substr() function produces an lvalue, that is, it may be assigned to. Therefore, to change the first character to an S, you could do this:

    
    substr($var,0,1) = 'S';

This assumes that $[ is 0; for a library routine where you can't know $[, you should use this instead:

    substr($var,$[,1) = 'S';
While it would be slower, you could in this case use a substitute:

    $var =~ s/^./S/;
But this won't work if the string is empty or its first character is a newline, which ``.'' will never match. So you could use this instead:

    $var =~ s/^[^\0]?/S/;

To do things like translation of the first part of a string, use substr, as in:

    substr($var, $[, 10) =~ tr/a-z/A-Z/;

If you don't know the length of what to translate, something like this works:

    /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
For some things it's convenient to use the /e switch of the substitute operator:

    s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e

although in this case, it runs more slowly than does the previous example.


Other resources at this site: