LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1517 min read

String Manipulation

Learn how to concatenate, measure, slice, search, split, and join strings using Perl's built-in string functions.

Introduction

Perl earned its reputation as a text-processing powerhouse largely because of how much string manipulation is built directly into the core language, with no need to import a library. This lesson covers the everyday toolbox: joining strings together, measuring and slicing them, changing case, searching inside them, and converting between strings and lists.

What You Will Learn
  • How to concatenate and repeat strings.
  • How to measure and slice strings with length and substr.
  • How to change case and search within strings.
  • How split and join convert between strings and arrays.

Concatenation

The dot operator (.) joins two strings together. There is also a combined dot-equals operator (.=) that appends to an existing variable, and the x operator, which repeats a string a given number of times.

use strict;
use warnings;
my $first = "Hello";
my $second = "World";
my $greeting = $first . ", " . $second . "!";
print "$greeting\n";
my $line = "-" x 10;
print "$line\n";
my $log = "Start";
$log .= " -> Processing";
$log .= " -> Done";
print "$log\n";
Program Output

Click Run to see what this code prints.

Remember that Perl also lets you interpolate variables directly inside double-quoted strings ("$first, $second!"), which often makes explicit concatenation with . unnecessary for simple cases.

length

The length function returns the number of characters in a string. It returns undef if given undef, so it is good practice to make sure the variable actually holds a string first.

use strict;
use warnings;
my $word = "Perl";
print "The word '$word' has ", length($word), " characters.\n";
Program Output

Click Run to see what this code prints.

substr

substr extracts a portion of a string. It takes the string, a starting offset (0-based, like array indices), and an optional length. Negative offsets count from the end of the string, which is a handy shortcut for grabbing the last few characters.

use strict;
use warnings;
my $filename = "report_2026.pdf";
my $extension = substr($filename, -3);
print "Extension: $extension\n";
my $name_only = substr($filename, 0, 11);
print "Name only: $name_only\n";
Program Output

Click Run to see what this code prints.

substr Can Also Replace Text

substr can be used on the left side of an assignment, or given a fourth "replacement" argument, to modify part of a string in place: substr($str, 0, 5) = "Howdy";

uc, lc, and Friends

Perl provides simple functions for changing case: uc converts a whole string to uppercase, lc converts to lowercase, ucfirst capitalizes only the first character, and lcfirst lowercases only the first character.

use strict;
use warnings;
my $name = "perl PROGRAMMING";
print uc($name), "\n";
print lc($name), "\n";
print ucfirst(lc($name)), "\n";
Program Output

Click Run to see what this code prints.

index

index searches for the first occurrence of a substring inside a string and returns its position, or -1 if it is not found at all. An optional third argument tells index where to start searching from, which is useful for finding all occurrences in a loop.

use strict;
use warnings;
my $sentence = "The quick brown fox jumps over the lazy dog";
my $position = index($sentence, "fox");
if ($position != -1) {
print "Found 'fox' at position $position\n";
} else {
print "'fox' not found\n";
}
my $missing = index($sentence, "cat");
print "Looking for 'cat' gave: $missing\n";
Program Output

Click Run to see what this code prints.

split

split breaks a string into a list of pieces based on a delimiter, which can be a plain string or a regular expression. This is one of the most commonly used functions when processing lines of data, such as CSV rows or log entries.

use strict;
use warnings;
my $csv_line = "Alice,28,Engineer";
my @fields = split(/,/, $csv_line);
print "Name: $fields[0]\n";
print "Age: $fields[1]\n";
print "Job: $fields[2]\n";
Program Output

Click Run to see what this code prints.

join

join does the opposite of split: it takes a list and glues its elements together into one string, using a delimiter you specify as the first argument.

use strict;
use warnings;
my @words = ('Perl', 'is', 'fun');
my $sentence = join(' ', @words);
print "$sentence\n";
my @path_parts = ('usr', 'local', 'bin');
my $path = join('/', @path_parts);
print "/$path\n";
Program Output

Click Run to see what this code prints.

Common Mistakes

Avoid These Mistakes
  • Forgetting that substr offsets are 0-based, off by one when slicing strings.
  • Using split(",", $line) with a plain comma when the field itself might contain a comma inside quotes (real CSV parsing needs a dedicated module, not a naive split).
  • Mixing up join's argument order — the delimiter always comes first, then the list.
  • Calling uc/lc on undef without checking, which triggers a warning under use warnings.
  • Assuming index returns 0 for "not found" — it actually returns -1; position 0 is a valid match at the very start of the string.

Best Practices

  • Prefer string interpolation ("$var") over manual concatenation with . when it keeps the code more readable.
  • Use split(/\s+/, $string) to split on any amount of whitespace rather than a single literal space.
  • Check for -1 explicitly after index rather than treating its return value as a boolean.
  • Reach for a real CSV-parsing module like Text::CSV for anything beyond the simplest comma-separated data.
  • Combine split and join to reformat data, such as turning a comma-separated line into a tab-separated one.

Frequently Asked Questions

split breaks a string into pieces around a delimiter and returns a list of the parts. The match operator (m// or =~) tests or extracts specific patterns without necessarily breaking the whole string apart.

Yes. substr($str, offset, length) = "new text"; replaces that portion of $str in place.

By default it counts characters as Perl currently understands the string's encoding. For proper Unicode handling, scripts typically add use utf8; and work with decoded strings.

Not a single built-in one, but it is a common one-liner using regular expressions: $str =~ s/^\s+|\s+$//g; which you will learn in the next lessons on regular expressions.

Key Takeaways

  • The dot operator (.) concatenates strings; x repeats them.
  • length measures a string; substr extracts or replaces part of one.
  • uc, lc, ucfirst, and lcfirst handle case conversion.
  • index searches for a substring and returns its position or -1.
  • split turns a string into a list; join turns a list back into a string.

Summary

These built-in string functions cover the everyday needs of text processing, but Perl's real superpower is regular expressions, which let you match and extract complex patterns in just a few characters. That is exactly where the next lesson takes you.

Next Lesson →

Regular Expressions