← Back to Perl Course | Chapter 3: Strings | Lesson 5 of 7

Case, trimming and characters

Small built-ins change case, trim line endings and swap characters.

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

perl
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
Common Mistakes
  1. Using chop when you only want to remove a newline
  2. Expecting reverse "abc" in list context to reverse the letters
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.