Programming Perl

Programming PerlSearch this book
Previous: 3.2.161 subChapter 3
Next: 3.2.163 symlink

3.2.162 substr


This function extracts a substring out of the string given by EXPR and returns it. The substring is extracted starting at OFFSET characters from the front of the string. (Note: if you've messed with $[, the beginning of the string isn't at 0, but since you haven't messed with it (have you?), it is.) If OFFSET is negative, the substring starts that far from the end of the string instead. If LENGTH is omitted, everything to the end of the string is returned. If LENGTH is negative, the length is calculated to leave that many characters off the end of the string. Otherwise, LENGTH indicates the length of the substring to extract, which is sort of what you'd expect.

You can use substr as an lvalue (something to assign to), in which case EXPR must also be a legal lvalue. If you assign something shorter than the length of your substring, the string will shrink, and if you assign something longer than the length, the string will grow to accommodate it. To keep the string the same length you may need to pad or chop your value using sprintf or the x operator.

To prepend the string "Larry" to the current value of $_, use:

substr($_, 0, 0) = "Larry";

To instead replace the first character of $_ with "Moe", use:

substr($_, 0, 1) = "Moe";

and finally, to replace the last character of $_ with "Curly", use:

substr($_, -1, 1) = "Curly";

These last few examples presume you haven't messed with the value of $[. You haven't, have you? Good.

Previous: 3.2.161 subProgramming PerlNext: 3.2.163 symlink
3.2.161 subBook Index3.2.163 symlink