In this tutorial, we will learn about strings in Perl. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.
A string in Perl is a sequence of characters. Strings in Perl can be created using single quotes, double quotes, or the qq
operator. Strings are used for storing and handling text data.
Strings can be created in Perl using single or double quotes:
my $str = "Hello, world!";
Strings can also be created using the qq
operator:
my $str2 = qq{Hello, world!};
print
.my $str = "Hello, world!";
print $str;
Hello, world!
my $str = "Hello";
print substr($str, 0, 1), "\n"; # Accessing using substr()
print substr($str, 1, 1), "\n";
H e
substr()
or append new characters.my $str = "Hello";
substr($str, 0, 1, 'J'); # Modifying individual character
$str .= " World!"; # Appending new characters
print $str;
Jello World!
.
operator.my $str1 = "Hello";
my $str2 = " World!";
my $str3 = $str1 . $str2; # Concatenating strings
print $str3;
Hello World!
index
function to find a substring.my $str = "Hello, world!";
my $pos = index($str, "world"); # Finding substring
if ($pos != -1) {
print "Found 'world' at position: $pos\n";
} else {
print "Substring not found\n";
}
Found 'world' at position: 7
length
function to get the length of the string.my $str = "Hello, world!";
print "Length of the string: ", length($str);
Length of the string: 13