Mike Gossland's Perl Tutorial Course for Windows

Introduction | String Functions | Array Functions | Test Functions | User Functions

Chapter 3. Functions

String Functions

String functions are functions that operate on strings or that return strings. We will just look at a couple of common ones here:

chop, chomp
chr, ord
lc, lcfirst, uc, ucfirst

chop and chomp

Strings often have trailing newlines after they have been read in as input. Chop and chomp are two functions used to clean up these strings by removing any trailing newline:


Chop is harsh - it chops off the last character no matter what it is. This is good if you want to remove a newline and the last character is a newline. But what if it isn't? Then you've chopped off the wrong thing. Chomp, which is a matching chop, will only remove the last character if it really is the newline character.

chr, ord

Chr returns the ascii character belonging to a numeric value, and ord returns the numeric value of the first character in a string:

chr(65) returns "A"; ord("Apple") returns 65;

lc, lcfirst, uc, ucfirst

These functions, representing lower case, lower case first character, upper case, and upper case first character, take a string and return the same string with obvious changes:

lc( "HELLO") returns "hello";
lcfirst ("HELLO" ) returns "hELLO";
uc("hello") returns ("HELLO");
ucfirst ("hello") returns ("Hello");


The length function returns the length of the string, including any newline characters:

length("hello") returns 5;


This useful function provides formatting capabilities for numbers and strings. Basically,

sprintf("%6.2f", $x );

would turn the numeric value of x into a string of characters with a precision of 2 decimal places and return that string value. You can read more about sprintf in the documentation.

concatenation, .

The dot operator, ., is actually an operator rather than a function, but I'll describe it here. A dot in Perl allows you to join two text scalars together. For example:

$x = "The quick ";
$y = "brown fox ";

$text = $x.$y."jumped over the lazy dog\n";

would put the whole sentence into the variable $text.