String Functions in Perl

The standard library’s string manipulation functions in Perl are built into the language itself. Here are some examples to give you a sense of string operations in Perl.

#!/usr/bin/env perl
use strict;
use warnings;

# We'll use print for output
sub p { print "@_\n" }

# Here's a sample of the string operations available in Perl.
# Unlike in some other languages, these are mostly built-in 
# operators or functions, not methods on string objects.

p "Contains:  ", "test" =~ /es/ ? "true" : "false";
p "Count:     ", () = "test" =~ /t/g;
p "HasPrefix: ", substr("test", 0, 2) eq "te" ? "true" : "false";
p "HasSuffix: ", substr("test", -2) eq "st" ? "true" : "false";
p "Index:     ", index("test", "e");
p "Join:      ", join("-", "a", "b");
p "Repeat:    ", "a" x 5;
p "Replace:   ", "foo" =~ s/o/0/gr;
p "Replace:   ", "foo" =~ s/o/0/r;
p "Split:     ", join(", ", split("-", "a-b-c-d-e"));
p "ToLower:   ", lc("TEST");
p "ToUpper:   ", uc("test");

When you run this program, you’ll get:

$ perl string_functions.pl
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      a, b, c, d, e
ToLower:    test
ToUpper:    TEST

In Perl, many string operations are performed using built-in functions or operators. For example, pattern matching with regular expressions is deeply integrated into the language, which makes operations like “contains” very straightforward.

The =~ operator is used for pattern matching and substitution. The /g flag in a regular expression makes it match globally (all occurrences).

Functions like substr(), index(), join(), split(), lc(), and uc() are built-in Perl functions for string manipulation.

The x operator is used for string repetition in Perl.

Note that Perl’s string substitution (s///) returns the number of substitutions by default. To get the modified string, we use the /r flag, which returns the result of substitution.

These examples show how Perl provides powerful string manipulation capabilities with its built-in functions and operators.