This time, Perl 101 visits some of Perl's more useful in-builtfunctions, and teaches you the basics of pattern matching and substitution.Also included is a list of common string and math functions, together withexamples of how to use them.
The next few string functions come in very handy when adjusting the case of a text string from lower- to upper-case, or vice-versa:
lc($string) - convert $string to lower case
uc($string) - convert $string to upper case
lcfirst($string) - convert the first character of $string to lower case
ucfirst($string) - convert the first character of $string to upper case
Here's an example:
#!/usr/bin/perl
# get a string
print "Say something: ";
chomp($string = );
# convert case
$output= lc($string);
print "All lower case: $output\n";
$output= uc($string);
print "All upper case: $output\n";
$output= lcfirst($string);
print "Look at the first character: $output\n";
$output = ucfirst($string);
print "Look at the first character: $output\n";
And here's the output:
Say something: Something's rotten in the state of Denmark
All lower case: something's rotten in the state of denmark
All upper case: SOMETHING'S ROTTEN IN THE STATE OF DENMARK
Look at the first character: something's rotten in the state of Denmark
Look at the first character: Something's rotten in the state of Denmark
The reverse() function is used to reverse the contents of a particular string.
#!/usr/bin/perl
# ask for input
print "Say something: ";
$something = ;
chomp ($something);
# reverse and print
$gnithemos = reverse($something);
print "Sorry, you seem to be talking backwards - what does $gnithemos
mean?";
Here's the output:
Say something: God, I'm good
Sorry, you seem to be talking backwards - what does doog m'I ,doG mean?
And the chr() and ord() functions come in handy when converting from ASCII codes to characters and vice-versa. For example,
print chr(65);
returns
A
while
print ord("a");
returns
97
This article copyright Melonfire 2000. All rights reserved.