Strings in Perl
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.
What is a String
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.
Creating Strings
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!};
Example 1: Initializing Strings
- Create a string variable and initialize it with a value.
- Print the string variable using
print
.
Perl Program
my $str = "Hello, world!";
print $str;
Output
Hello, world!
Example 2: Accessing Characters in a String
- Create a string variable and initialize it with a value.
- Access and print individual characters using array indexing.
Perl Program
my $str = "Hello";
print substr($str, 0, 1), "\n"; # Accessing using substr()
print substr($str, 1, 1), "\n";
Output
H e
Example 3: Modifying Strings
- Create a string variable and initialize it with a value.
- Strings in Perl are mutable, so you can modify individual characters directly using
substr()
or append new characters. - Print the modified string.
Perl Program
my $str = "Hello";
substr($str, 0, 1, 'J'); # Modifying individual character
$str .= " World!"; # Appending new characters
print $str;
Output
Jello World!
Example 4: String Concatenation
- Create two string variables and initialize them with values.
- Concatenate the strings using the
.
operator. - Print the concatenated string.
Perl Program
my $str1 = "Hello";
my $str2 = " World!";
my $str3 = $str1 . $str2; # Concatenating strings
print $str3;
Output
Hello World!
Example 5: Finding Substrings
- Create a string variable and initialize it with a value.
- Use the
index
function to find a substring. - Print the position of the found substring.
Perl Program
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";
}
Output
Found 'world' at position: 7
Example 6: String Length
- Create a string variable and initialize it with a value.
- Use the
length
function to get the length of the string. - Print the length of the string.
Perl Program
my $str = "Hello, world!";
print "Length of the string: ", length($str);
Output
Length of the string: 13