Strings and regular expressions

String functions, printf, matching with =~, capture groups, /g, and substitution with s///r.

Runs in Zerethon IDE · Perl 5.40 Official Perl documentation ↗
main.pl
use v5.40;

my $name = "Ada Lovelace";
say "$name has ", length($name), " characters";
say uc($name), " ", lc($name), " ", substr($name, 0, 3);
say "  padded  " =~ s/^\s+|\s+$//gr, "|";
say join("|", split /,/, "a,b,c"), " ", join("-", qw(x y z));
say $name =~ s/Ada/Augusta/r, " ", ($name =~ /^Ada/ ? "starts" : "no"), " ", index(lc $name, "love");
printf "%.2f %5d %03d\n", 3.14159, 42, 7;

my $text = "Order 12 shipped, order 7 pending";
my @numbers = $text =~ /(\d+)/g;
say "@numbers";
if ($text =~ /order (\d+) pending/) {
    say "pending: $1";
}
(my $doubled = $text) =~ s/(\d+)/$1 * 2/ge;
say $doubled;
say "x" x 3, " ", "a" . "b";

Output

Ada Lovelace has 12 characters
ADA LOVELACE ada lovelace Ada
padded|
a|b|c x-y-z
Augusta Lovelace starts 4
3.14    42 007
12 7
pending: 7
Order 24 shipped, order 14 pending
xxx ab
  • $text =~ /pattern/ tests for a match; captures go to $1, $2… Only use them right after a match that succeeded.
  • s/old/new/ changes the variable in place; with /r it returns the changed copy and leaves the original alone. /g replaces every match, /e evaluates the replacement as code, /i ignores case.
  • index returns the position of a substring, or -1 when it is not there.
  • x repeats a string; . joins two strings.