next up previous contents
Next: Array Functions Up: Functions Previous: Using a Private Function

String Functions

Perl provides a very useful set of string handling functions:

The first set of functions that we'll look at are those that deal with strings. These functions let you determine a string's length, search for a sub-string, and change the case of the characters in the string, among other things.

Here are Perl's string functions:

Note As a general rule, if Perl sees a number where it expects a string, the number is quietly converted to a string without your needing to do anything.

Note Some of these functions use the special variable $_ as the default string to work with. More information about $_ can be found in Chapter on Files, and the Chapter Special Variables.

The next few sections demonstrate some of these functions. After seeing some of them work, you'll be able to use the rest of them.

Example: Changing a String's Value

Frequently, I find that I need to change part of a string's value, usually somewhere in the middle of the string. When this need arises, I turn to the substr() function. Normally, the substr() function returns a sub-string based on three parameters: the string to use, the position to start at, and the length of the string to return.

$firstVar = substr("0123BBB789", 4, 3);

print("firstVar  = $firstVar\n");

This program prints:

firstVar = BBB

The substr() function starts at the fifth position and returns the next three characters. The returned string can be printed like in the above example, as an array element, for string concatention, or any of a hundred other options.

Things become more interesting when you put the substr() function on the left-hand side of the assignment statement. Then, you actually can assign a value to the string that substr() returns.

$firstVar = "0123BBB789";

substr($firstVar, 4, 3) = "AAA";

print("firstVar  = $firstVar\n");

This program prints:

firstVar = 0123AAA789

Example: Searching a String

Another useful thing you can do with strings is search them to see if they have a given sub-string. For example if you have a full path name such as


you might need to extract the file name at the end of the path. You might do this by searching for the last backslash and then using substr() to return the sub-string.

Note The path name string has double backslashes to indicate to Perl that we really want a backslash in the string and not some other escape sequence,

$pathName = "C:\\WINDOWS\\TEMP\\WSREWE.DAT";

$position = rindex($pathName, "\\") + 1;

$fileName = substr($pathName, $position);


This program prints:


If the third parameter-the length-is not supplied to substr(), it simply returns the sub-string that starts at the position specified by the second parameter and continues until the end of the string specified by the first parameter.

next up previous contents