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.
You can also search for specific patterns in your strings with regular expressions, something that Perl supports better than most other languages.
In Perl, all interaction with regular expressions takes place via an equality operator, represented by =~
$flag =~ m/susan/
$flag returns true if $flag contains "susan" using the "m" operator.
You can also perform string substitution with regular expressions with the "s" operator, as in the following exanple.
$flag =~ s/susan/JANE/
This replaces "susan" in the variable $flag with "JANE" using the "s" operator.
Here is a simple example that validates an email address:
# get input
print "So what's your email address, anyway?\n";
# match and display result
print("Ummmmm....that sounds good!\n");
print("Hey - who do you think you're kidding?\n");
Obviously, this is simply an illustrative example - if you're planning to use it on your Web site, you need to refine it a bit. You have been warned!
If you want to find out the number of times a particular pattern has been repeated in a string, Perl offers the very cool "tr" operator.
# get input
print "Gimme a string: ";
# put string into default variable for tr
$_ = $string;
# check string for spaces and print result
$blanks += tr/ / /;
print ("There are $blanks blank characters in \"$string\".");
Here's an example session:
Gimme a string: This is a test.
There are 3 blank characters in "This is a test.".
You can have Perl return the position of the last match in a string with the pos() function,
$string = "The name's Bond, James Bond";
# search for the character d
$string =~ /d/g;
# returns 15
and automatically quote special characters with backslashes with the quotemeta() function.