Perl has always been known for its text processing and manipulation abilities. This article examines the Perl string handling API in greater detail, explaining how you can use Perl's string functions to (among other things) print and format strings, split and join string values, alter string case, and perform regular expression searches.
We'll begin right at the top, with some very basic definitions and concepts.
In Perl, the term "string" refers to a sequence of characters. The following are all valid examples of strings:
"I'm back!"
"by golly miss molly"
"a long time ago in a galaxy far, far away"
String values can be assigned to a variable using the standard assignment operator.
$identity = "Jedi";
String values may be enclosed in either double quotes ("") or single quotes('') - the following variable assignments are equivalent"
$character = "Luke";
$character = 'Luke';
String values enclosed in double quotes are automatically parsed for variable names; if variable names are found, they are automatically replaced with the appropriate variable value.
#!/usr/bin/perl
$character = "Chewbacca";
$race = "Wookie";
# this would contain the string "Chewbacca is a Wookie" $sentence =
"$character is a $race";
Perl also allows you to create strings which span multiple lines. The original formatting of the string, including newlines and whitespace, is retained when such a string is printed.
The << symbol indicates to Perl that what comes next is a multi-line block of text, and should be printed as is right up to the marker "EOF". This comes in very handy when you need to output a chunk of HTML code, or any other multi-line string.
Strings can be concatenated with the string concatenation operator, represented by a period(.)
#!/usr/bin/perl
# set up some string variables
$a = "the cow ";
$b = "jumped over ";
$c = "the moon ";
# combine them using the concatenation operator
# this returns "the cow jumped over the moon"
$statement = $a . $b . $c;
# and this returns "the moon jumped over the cow"
$statement = $c . $b . $a;
Note that if your string contains quotes, carriage returns or backslashes, it's necessary to escape these special characters with a backslash.
# will cause an error due to mismatched quotes
$film = 'America's Sweethearts';
# will be fine
$film = 'America\'s Sweethearts';
The print() function is used to output a string or string variable.
#!/usr/bin/perl
# string
print "Last Tango In Paris";
# string variable
$film = "Last Tango In Paris";
print $film;
But if you thought that all you can do is concatenate and print strings, think again - you can also repeat strings with the repetition operator, represented by the character x.
#!/usr/bin/perl
# set a string variable
$insult = "Loser!\n";
# repeat it
print($insult x 7);