* changed the title (updated + get rid of the / + expand the answer to include changes to any part of the string + talk about characters, not just letters * the answer now shows the fourth argument to substr()
* the $first_byte variable is now the $first_char variable because it isn't necessarily a byte. --- perlfaq.pod 5 Sep 2002 00:48:40 -0000 1.12 +++ perlfaq.pod 4 Nov 2002 20:41:55 -0000 @@ -405,7 +405,7 @@ =item * -How can I access/change the first N letters of a string? +How can I access or change N characters of a string? =item * Index: perlfaq4.pod =================================================================== RCS file: /cvs/public/perlfaq/perlfaq4.pod,v retrieving revision 1.35 diff -u -d -r1.35 perlfaq4.pod --- perlfaq4.pod 30 Oct 2002 18:40:34 -0000 1.35 +++ perlfaq4.pod 4 Nov 2002 20:41:57 -0000 @@ -650,23 +650,25 @@ See the documentation for Text::Autoformat to appreciate its many capabilities. -=head2 How can I access/change the first N letters of a string? - -There are many ways. If you just want to grab a copy, use -substr(): +=head2 How can I access or change N characters of a string? - $first_byte = substr($a, 0, 1); +You can access the first characters of a string with substr(). +To get the first character, for example, start at position 0 +and grab the string of length 1. -If you want to modify part of a string, the simplest way is often to -use substr() as an lvalue: - substr($a, 0, 3) = "Tom"; + $string = "Just another Perl Hacker"; + $first_char = substr( $string, 0, 1 ); # 'J' -Although those with a pattern matching kind of thought process will -likely prefer +To change part of a string, you can use the optional fourth +argument which is the replacement string. - $a =~ s/^.../Tom/; + substr( $string, 13, 4, "Perl 5.8.0" ); + +You can also use substr() as an lvalue. + substr( $string, 13, 4 ) = "Perl 5.8.0"; + =head2 How do I change the Nth occurrence of something? You have to keep track of N yourself. For example, let's say you want
