Perl Strings


Perl Strings

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!};


Initializing Strings

  1. Create a string variable and initialize it with a value.
  2. Print the string variable using print.

Perl Program

my $str = "Hello, world!";
print $str;

Output

Hello, world!


Accessing Characters in a String

  1. Create a string variable and initialize it with a value.
  2. 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


Modifying Strings

  1. Create a string variable and initialize it with a value.
  2. Strings in Perl are mutable, so you can modify individual characters directly using substr() or append new characters.
  3. 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!


String Concatenation

  1. Create two string variables and initialize them with values.
  2. Concatenate the strings using the . operator.
  3. Print the concatenated string.

Perl Program

my $str1 = "Hello";
my $str2 = " World!";
my $str3 = $str1 . $str2; # Concatenating strings
print $str3;

Output

Hello World!


Finding Substrings

  1. Create a string variable and initialize it with a value.
  2. Use the index function to find a substring.
  3. 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


String Length

  1. Create a string variable and initialize it with a value.
  2. Use the length function to get the length of the string.
  3. 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