Perl Scripts ·
Perl Strings and Regex: substr, Replace and Rounding
By Manu Mathew, Technical Lead Engineer · Published 4 October 2026 · Last updated 5 October 2026

Text handling is where Perl earned its reputation, and a few tools cover most daily needs: substr, the substitution operator and sprintf. This page brings together several short notes on Perl strings I wrote in 2014. I have rewritten them in one place, with tested examples and current advice, so you don’t have to piece the answer together from fragments.
Quick answer
substr($s, $offset, $length) takes part of a string, and negative offsets count from the end. s/old/new/ replaces the first match; add /g for every match and /r to return a new string. Wrap literal text in \Q…\E. Reorder parts with capture groups, and format decimals with sprintf '%.2f'.
I tested each example with Perl 5.40, using use strict and use warnings.
How do I take part of a string with substr?
Give substr the string, a starting offset and, optionally, a length; a fourth argument replaces that part in place.
use strict;
use warnings;
my $word = 'okay';
print substr($word, 2), "\n"; # ay (from offset 2 to the end)
print substr($word, 1, 2), "\n"; # ka (2 characters from offset 1)
print substr($word, -1), "\n"; # y (negative offsets count from the end)
my $text = 'Hello world';
substr($text, 0, 5, 'Hi'); # 4-argument form replaces in place
print "$text\n"; # Hi world
How do I replace text in a string?
Use the substitution operator s///: it changes the first match, or every match with /g.
use strict;
use warnings;
my $text = 'cat and cat food';
(my $one = $text) =~ s/cat/dog/; # first match only
print "$one\n"; # dog and cat food
my $all = $text =~ s/cat/dog/gr; # /g every match, /r returns a new string
print "$all\n"; # dog and dog food
# Replace literal text that may contain regex characters
my ($from, $to) = ('1+1', 'two');
(my $sum = 'Is 1+1 easy?') =~ s/\Q$from\E/$to/g;
print "$sum\n"; # Is two easy?
The older note wrapped this in a replace() subroutine. That is fine, but it passed the search text straight into the pattern, so characters such as +, . or ( changed its meaning. \Q…\E makes the text literal. The /r flag (Perl 5.14 and later) returns the changed copy and leaves the original alone.
How do I reorder parts of a string, such as a date?
Capture each part with parentheses, then put the captures back in the order you want.
use strict;
use warnings;
my $date = '2009-02-27'; # YYYY-MM-DD
(my $uk = $date) =~ s{(\d{4})-(\d{2})-(\d{2})}{$3/$2/$1};
print "$uk\n"; # 27/02/2009
# Named captures make the intent clearer
if ($date =~ /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/) {
print "$+{m}/$+{d}/$+{y}\n"; # 02/27/2009
}
Using s{…}{…} instead of slashes means the / characters in the replacement don’t need escaping. Named captures ((?<y>…), read back through %+) make longer patterns easier to follow. For real date handling, parse the date with Time::Piece and format it again.
How do I show a number with a fixed number of decimals?
sprintf '%.2f' rounds to two decimal places and returns a string; printf prints it directly.
use strict;
use warnings;
printf "%.2f\n", '10.0500000'; # 10.05
my $rounded = sprintf '%.2f', 3.14159;
print "$rounded\n"; # 3.14
# Binary floating point can surprise you on exact halves
printf "%.2f\n", 1.005; # 1.00, because 1.005 is stored as 1.00499999...
Numbers like 1.005 can’t be stored exactly in binary, so they may round down. For money, store whole units (paise or cents) as integers and format them only for display.
How do I print JavaScript or other text that contains $ signs?
Use a heredoc with single quotes around its marker, <<'JS', so Perl prints the text exactly as written and leaves every $ alone.
use strict;
use warnings;
my $selector = '#scroller';
# Single-quoted heredoc: nothing is interpolated, so $ is safe as written
print <<'JS';
<script>
$(function () { $('.menu').addClass('ready'); });
</script>
JS
# Double-quoted heredoc: escape the $ signs that belong to JavaScript
print <<"JS";
<script>
\$(function () { \$('$selector').show(); });
</script>
JS
The second form is for when you do need a Perl variable inside: $selector is filled in, and each \$ reaches the browser as a plain $. An older note on this site did this with print qq{…} and an escaped $ on every line; a single-quoted heredoc is easier to read and harder to get wrong. See perlop: quote and quote-like operators.
Need help? If your Perl string handling is part of an older application that needs fixing or updating, I can take a look. See Perl development, or email manu@manu.co.in.
Frequently asked questions
Should I use substr or a regex to pull out part of a string?
substr works by position and length, so it suits fixed formats such as codes or dates in known places. A regex works by pattern, which suits text where the position varies. When the positions are fixed, substr is the simpler one to read.
How do I trim spaces from the start and end of a string?
On Perl 5.40 or later, use v5.40; makes trim available, so trim($text) removes leading and trailing whitespace. On older versions, use the substitution s/^\s+|\s+$//g, which does the same in one line.
How do I make a match ignore case?
Add the /i flag, as in $city =~ /kozhikode/i. To compare two whole strings regardless of case, use fc($a) eq fc($b) with use feature 'fc', which also handles non-English letters correctly.
Why does sprintf(‘%.2f’, 2.675) print 2.67?
Because 2.675 can’t be stored exactly in binary floating point. The stored value is slightly below 2.675, so it rounds down. For money, store whole paise or cents as integers and format them only for display, or use a decimal module such as Math::BigFloat.
Related notes: removing the last character with chop(); removing newlines with chomp(); checking whether a Perl variable is a number; hiring a remote Perl developer.
Need help with Perl code?
If you have Perl code that needs fixing, extending or upgrading, I’m happy to take a look. I work remotely from Kozhikode, Kerala, with teams across India and elsewhere; Perl development and maintenance explains how I help. If you are deciding how to bring someone in, Hiring a remote Perl developer is a short checklist.
You can reach me through the contact section or email me at manu@manu.co.in. A few lines about the system and what you need is a good start.
Sources: perlfunc: substr; perlop: s/// and its modifiers; perlre: capture groups; perlfunc: sprintf; perlfaq4: why am I getting long decimals?.