Built-in Subroutines

Let's discuss the built-in subroutines used for performing various string operations in this lesson.

Extracting substrings

A string can possibly be divided into multiple pieces based on a separator. If the separator is “” (empty string), then each character will be extracted separately. The split subroutine is used for this purpose. If the separator is some other string, then it will become the cut point of the string. The cut point itself will not be stored as a piece of string. The split subroutine returns an array of substrings. This subroutine takes two parameters: the separator and the input string.

To extract a substring from the given string, substr is used. This subroutine takes three arguments parameters: input string, start index of the substring to be extracted, and length of the substring to be extracted. The following code snippet implements both of these subroutines.

Note: Strings, like everything in Perl, are 0-indexed, i.e. their first character is at index 0.

Press + to interact
$foo = "Hello world";
@arr = split("",$foo);
print $arr[6]; # returns w
print "\n";
print substr($foo, 6, 5); # returns 'world'

Ways to display strings

We can use multiple ways to display a string in Perl. In the code given below, we will be using q^^, q{}, '', "", and qq to display a string. To add special characters in our code, we can use backslash \. Let’s look at the implementation:

Press + to interact
$str = q^A string with \^\^ delimiter ^;
$str1 = q{A string with q delimiter };
$str2 = 'A string with \'\' delimiter';
$str3 = "A string with \"\" delimiter";
$str4 = qq{A string with qq delimiter };
print $str , "\n";
print $str1 , "\n";
print $str2 , "\n";
print $str3 , "\n";
print $str4 , "\n";

Finding position of a substring

In Perl, we can use the index method to get the first position/occurrence of a substring in another string. If the substring does not exist, the index returns -1.

Press + to interact
$str = "The occurence of hay is hay at position:";
print $str . index($str, "hay")."\n";

Changing letter case of a string

In Perl, an input string can be converted into an uppercase or lowercase using uc or lc subroutines, respectively.

Press + to interact
$foo = 'hello world';
$foo2 = 'HELLO WORLD';
print uc($foo), "\n"; # convert string to upper case
print lc($foo2), "\n"; # convert string to lower case

Calculating the length of a string

The length() subroutine is used to calculate the number of characters inside a string. It also includes the blank spaces inside the string.

Press + to interact
$my_str = 'Welcome to Educative!';
print length($my_str); # returns 21 which is number of characters

Reversing a string

The reverse method in Perl can be used to reverse a string.

Press + to interact
$my_str = '!lrep gninraeL';
# Display reversed string
$print = reverse($my_str);
print $print;