String Functions
Perl has a large set of built-in functions for working with strings. This lesson covers the ones you will use every day.
| Function | Purpose | Example | Result |
|---|---|---|---|
length |
number of characters | length "camel" |
5 |
uc, lc |
upper / lower case | uc "perl" |
PERL |
ucfirst, lcfirst |
change the first character | ucfirst "ada" |
Ada |
index |
position of a substring | index "banana", "an" |
1 |
rindex |
last position of a substring | rindex "banana", "an" |
3 |
substr |
extract or replace part of a string | substr "Perl", 1, 2 |
er |
reverse (scalar) |
reverse the characters | scalar reverse "abc" |
cba |
chomp |
remove a trailing newline | chomp $line |
|
sprintf |
format a string | sprintf "%05d", 42 |
00042 |
fc |
case-fold for comparisons | fc "HeLLo" |
hello |
length, case and chomp
use strict;
use warnings;
my $input = "hello world\n";
print "Raw length: ", length($input), "\n";
chomp $input;
print "After chomp: ", length($input), "\n";
print uc($input), "\n";
print ucfirst($input), "\n";
print join(" ", map { ucfirst lc } split / /, "tHE gREAT gATSBY"), "\n";Raw length: 12
After chomp: 11
HELLO WORLD
Hello world
The Great Gatsby
chomp removes one trailing newline if there is one, and is safe to call on strings without a newline. Its older cousin chop removes the last character no matter what, which is rarely what you want.
Inside double-quoted strings you can also use the escapes \U...\E (upper), \L...\E (lower), \u and \l (first character): "\u\L$name" turns mARY into Mary.
index and rindex
index(STRING, SUBSTRING, START) returns the position of the first occurrence (counting from 0), or -1 if it is not found:
use strict;
use warnings;
my $path = "/var/log/app/server.log";
print "First /: ", index($path, "/"), "\n";
print "Last /: ", rindex($path, "/"), "\n";
print "'log' from position 6: ", index($path, "log", 6), "\n";
print "'tmp': ", index($path, "tmp"), "\n";
my $file = substr($path, rindex($path, "/") + 1);
print "File name: $file\n";
my @positions;
my $pos = -1;
push @positions, $pos while ($pos = index("banana", "a", $pos + 1)) != -1;
print "'a' found at: @positions\n";First /: 0
Last /: 12
'log' from position 6: 20
'tmp': -1
File name: server.log
'a' found at: 1 3 5
Warning: Test the result of
indexagainst-1, not for truth. A match at position 0 returns0, which is false!
substr
substr(STRING, OFFSET, LENGTH) extracts part of a string. A negative offset counts from the end, and if you leave out LENGTH you get the rest of the string. With a fourth argument, or used on the left of =, it replaces that part:
use strict;
use warnings;
my $isbn = "978-0-596-52724-2";
print "Prefix: ", substr($isbn, 0, 3), "\n";
print "Check digit: ", substr($isbn, -1), "\n";
print "From 6: ", substr($isbn, 6), "\n";
my $card = "4111222233334444";
substr($card, 0, 12) = "*" x 12;
print "Masked: $card\n";
my $msg = "I like tea";
substr($msg, 7, 3, "coffee");
print "$msg\n";Prefix: 978
Check digit: 2
From 6: 596-52724-2
Masked: ************4444
I like coffee
Padding, trimming and repeating
Perl has no built-in trim, but a substitution does the job. For padding, sprintf (next lesson) is the tool:
use strict;
use warnings;
my $raw = " spaced out ";
(my $trimmed = $raw) =~ s/^\s+|\s+$//g;
print "[$trimmed]\n";
printf "[%-10s]\n", "left";
printf "[%10s]\n", "right";
printf "[%s]\n", "-" x 10;
my $long = "A very long sentence that needs shortening";
my $short = length($long) > 20 ? substr($long, 0, 17) . "..." : $long;
print "$short\n";[spaced out]
[left ]
[ right]
[----------]
A very long sente...
Comparing without case
To compare strings case-insensitively, compare their folded forms. fc (enabled with use feature 'fc') is the correct Unicode way; lc works for plain English text:
use strict;
use warnings;
use feature 'fc';
my @names = qw(bob Alice carol Dave);
print "Default sort: @{[ sort @names ]}\n";
print "Case-insensitive: @{[ sort { fc($a) cmp fc($b) } @names ]}\n";
print "Same? ", (fc("PERL") eq fc("perl") ? "yes" : "no"), "\n";Default sort: Alice Dave bob carol
Case-insensitive: Alice bob carol Dave
Same? yes
Uppercase letters sort before lowercase ones by default, because they come first in the character table.
Test yourself
What does index("hello", "z") return?
- 0
- undef
- -1
- an error
What is substr("Perl rocks", -5)?
PerlrocksrPerl
Why prefer chomp over chop for input lines?
chompis fasterchomponly removes a trailing newline,chopalways removes the last characterchopdoesn't exist- There is no difference