Case, trimming and characters
Small built-ins change case, trim line endings and swap characters.
In this page:
Case, trimming and characters
uc, lc, ucfirst and lcfirst change the case of a string, and reverse in scalar context reverses its characters. chomp removes a trailing newline and chop removes the last character. The tr/// operator translates characters one for one and, in scalar context, returns how many characters it matched.
Note:
chomp only removes the newline (the value of $/), so it is safe to call even when no newline is there.
Example: Case, trimming and characters
use strict;
use warnings;
my $line = " perl programming \n";
chomp $line;
print "chomped: [$line]\n";
(my $trimmed = $line) =~ s/^\s+|\s+$//g;
print "trimmed: [$trimmed]\n";
print "uc: ", uc($trimmed), "\n";
print "ucfirst: ", ucfirst($trimmed), "\n";
print "reversed: ", scalar reverse($trimmed), "\n";
(my $dna = "ATGC") =~ tr/ATGC/TACG/;
print "complement: $dna\n";
my $vowels = ($trimmed =~ tr/aeiou//);
print "vowels: $vowels\n";
my $word = "chopper";
chop $word;
print "chopped: $word\n";
# Output:
# chomped: [ perl programming ]
# trimmed: [perl programming]
# uc: PERL PROGRAMMING
# ucfirst: Perl programming
# reversed: gnimmargorp lrep
# complement: TACG
# vowels: 4
# chopped: choppe
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using chop when you only want to remove a newline
- Expecting reverse "abc" in list context to reverse the letters
- Trying to trim spaces with chomp
Chapter Summary
- uc, lc, ucfirst and lcfirst change case
- chomp removes a trailing newline
- scalar reverse reverses a string
- tr/// translates or counts characters
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: