Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 43 ยท Scalars and Operators

Working with Strings

Work with Perl strings: length, substr (including 4-argument and lvalue forms), index, uc and lc, the x operator, join, reverse, sprintf, chomp and chop.

Strings are what Perl was built for, and the language comes with a long list of built-in functions for slicing, searching, changing case and formatting them. In this lesson you will learn the ones you will use every day: length, substr, index, uc and lc, the repeat operator x, join, reverse, sprintf, and the line-ending tools chomp and chop.

If you are not sure how quoting and interpolation work, read Scalar Variables first. Regular expressions, the other great string tool, have their own chapter starting at Regular Expressions Basics.

Perl does not run on this site, so Perl blocks are read-only with real output from Perl 5.42 below them. The TryIts are Python stand-ins that perform the same operations with Python's equivalents, so you can experiment with the ideas.

length

length returns the number of characters in a string. It returns undef for an undefined value, so give it a real string:

PERL
use v5.36;

my $s = "Hello, Perl";
say length $s;
say length "";
say length 12345;
TEXT
11
0
5

Numbers are strings too, so length 12345 counts its five digits.

Functions that look inside a string

substr Cut out or replace a piece.
index Find where a piece starts.
length Count the characters.

Positions start at 0, and negative numbers count from the end.

1 / 2

substr

substr extracts part of a string. The arguments are the string, the offset (counting from 0), and an optional length:

PERL
use v5.36;

my $s = "Hello, Perl";

say substr($s, 0, 5);
say substr($s, 7);
say substr($s, -4);
say substr($s, 2, -2);
TEXT
Hello
Perl
Perl
llo, Pe
  • With no length, substr goes to the end.
  • A negative offset counts from the end, so -4 means "the last four characters".
  • A negative length means "stop that many characters before the end".

Changing a string with substr

substr can also replace text. You can assign to it, or pass a fourth argument:

PERL
use v5.36;

my $s = "Hello, Perl";

my $t = $s;
substr($t, 0, 5) = "Howdy";
say $t;

my $u = $s;
substr($u, 0, 5, "Bye");
say $u;
TEXT
Howdy, Perl
Bye, Perl

Both forms replace the selected part, and the string changes in place. The replacement does not need to be the same length.

Python Stand-in: slicing with Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python's slices use a start and a stop position, where Perl's substr uses a start and a length. The results match, but be careful when you translate between the two.

index and rindex

index finds the position of a piece of text and returns -1 when it is not found. An optional third argument says where to start searching. rindex searches from the right:

PERL
use v5.36;

my $s = "Hello, Perl";

say index($s, "l");
say index($s, "l", 4);
say rindex($s, "l");
say index($s, "z");
TEXT
2
10
10
-1

The first "l" is at position 2. Starting the search at position 4 skips the first two and finds the one at 10. Always compare the result to -1 rather than testing it as true or false, because position 0 is a valid result and also false.

Changing case

PERL
use v5.36;

my $s = "Hello, Perl";

say uc $s;
say lc $s;
say ucfirst lc "pERL";
say lcfirst "ABC";
TEXT
HELLO, PERL
hello, perl
Perl
aBC

uc and lc convert the whole string, ucfirst and lcfirst only the first character. Combining them, as in ucfirst lc $name, is the usual way to normalize a name. Comparing strings in a case-insensitive way is easy: compare lc $a with lc $b.

Repeating with x

The x operator repeats a string. It is perfect for drawing lines and padding:

PERL
use v5.36;

say "-" x 10;
say "ab" x 2.7;
my @l = ("a") x 3;
say "@l";
TEXT
----------
abab
a a a
  • The count is rounded down, so 2.7 becomes 2. A negative count produces an empty string (and a warning).
  • When the left side is in parentheses and you assign to an array, x repeats a list, as in my @l = ("a") x 3;. You will use this to make an array of defaults.

join and reverse

join glues a list together with a separator between each item:

PERL
use v5.36;

say join ", ", "x", "y", "z";
say scalar reverse "stressed";
TEXT
x, y, z
desserts

The second line shows an important detail about reverse. In scalar context it reverses the characters of a string. In list context it reverses the order of its arguments:

PERL
use v5.36;

say reverse("ab", "cd");
say scalar reverse("ab", "cd");
TEXT
cdab
dcba

The first line gets list context from say, so it only swaps the two items. The second forces scalar context with scalar, which joins all the arguments and reverses the characters. Context is the subject of Context: Scalar vs List. To reverse one string safely, always write scalar reverse $s.

sprintf and printf

sprintf builds a string from a template with placeholders, and printf prints it directly. It is the tool for padding, rounding and aligning numbers. The most useful placeholders:

Placeholder Meaning
%s a string
%d an integer (decimals are cut off)
%f a decimal; %.2f means two decimals
%x hexadecimal; %b binary; %o octal
%e scientific notation
%% a literal percent sign

Numbers between % and the letter control the width: %5d pads to five columns, %-6s pads on the right (left-aligned), and %06d pads with zeros.

PERL
use v5.36;

say sprintf("%5.2f|%-6s|%06d|%x|%e|%3d%%", 3.14159, "ab", 42, 255, 12345.678, 50);
printf("%s is %d years\n", "Ada", 36);
say sprintf("%+d", 5);
say sprintf("%b", 10);
say sprintf("%.3s", "abcdef");
say sprintf("%d", 3.99);
say sprintf("%-10s|%8.2f|", "Apple", 1.5);
TEXT
 3.14|ab    |000042|ff|1.234568e+04| 50%
Ada is 36 years
+5
1010
abc
3
Apple     |    1.50|

%d truncates 3.99 to 3; it does not round. Use %.0f to round. Note that printf does not add a newline, so put \n in the template.

Python Stand-in: formatting with Python's % operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Perl's %b for binary is not in Python's % operator (Python uses the bin function or the format "{:b}"), so it is left out of this stand-in; otherwise the placeholders behave the same.

chomp and chop

When you read a line from a file or from the keyboard, it ends with a newline character. chomp removes a trailing newline, and only if there is one. chop removes the last character, whatever it is:

PERL
use v5.36;

my $line = "text\n";
chomp $line;
say "[$line]";
chomp $line;
say "[$line]";

my $c = "hello";
chop $c;
say $c;

my $removed = chomp(my $x = "abc\n");
say $removed;
TEXT
[text]
[text]
hell
1

The second chomp does nothing because there is no newline left, which makes it safe to call twice. chomp returns how many characters it removed, here 1. Prefer chomp for input lines; chop is rarely the right tool.

Putting it together

Here is a short real-life example that combines several functions: it formats a name, builds a report line, and draws a rule under it.

PERL
use v5.36;

my $name  = "aDA LOVELACE";
my $nice  = join " ", map { ucfirst lc } split ' ', $name;
my $line  = sprintf("%-15s|%6.2f", $nice, 1234.5);

say $line;
say "=" x length $line;
TEXT
Ada Lovelace   |1234.50
=======================

The map and split pieces are covered in List Functions and Sorting. For now, notice how small each step is, and how length sizes the underline to match the text.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does substr("Hello, Perl", -4) return?

    A negative offset counts from the end of the string, so -4 selects the last four characters.
  2. 2. What does index("banana", "z") return?

    index returns -1 when the text is not found. 0 would mean a match at the very start.
  3. 3. What is the difference between chomp and chop?

    chomp removes a trailing newline if there is one, which is what you want for input lines. chop always removes the final character.
  4. 4. What does say scalar reverse("ab", "cd") print?

    In scalar context reverse joins its arguments and reverses the characters, giving dcba. In list context it would only reverse the order of the items.
  5. 5. What does sprintf("%d", 3.99) return?

    %d truncates toward zero instead of rounding. Use %.0f to round to the nearest integer.

Summary

  • length counts characters; substr extracts or replaces a piece, with negative offsets counting from the end.
  • index and rindex find text and return -1 when it is missing.
  • uc, lc, ucfirst and lcfirst change case; x repeats strings or lists; join glues a list together.
  • reverse reverses characters only in scalar context, so write scalar reverse $s.
  • sprintf and printf format values with placeholders such as %s, %d, %.2f and %-10s.
  • chomp removes a trailing newline safely; chop removes the last character.

Next: Operators and Numbers.