perl function substr

The substr function in Perl is used to extract a substring from a string or to replace a substring within a string with another string.

Here's an example of using substr to extract a substring from a string:

refer t‮‬o:theitroad.com
my $string = "Hello, world!";
my $substring = substr($string, 7, 5); # Extract "world" starting from index 7

print "Substring: $substring\n"; # Output: "world"

In this example, the substr function is called with three arguments: the string to extract the substring from ($string), the index of the first character of the substring (7), and the length of the substring (5). The resulting substring is assigned to the variable $substring.

Here's an example of using substr to replace a substring within a string:

my $string = "Hello, world!";
substr($string, 7, 5) = "Perl"; # Replace "world" with "Perl" starting from index 7

print "New string: $string\n"; # Output: "Hello, Perl!"

In this example, the substr function is called with the same three arguments as before, but this time the assignment operator is used to replace the resulting substring with the new string "Perl". The resulting modified string is then printed to the console.