1. Perl
  2. builtin functions
  3. here

substr function - extract/replace string

You can use the substr function to extract or replace the part of the string. The first argument is a string, the second argument is the start index, and the third argument is the cutout length. The index starts at 0. If the 3rd argument is omitted, the target will be up to the end of string.

# Extract
my $word_like = substr($message, 2, 4);

To replace the string at the specified index, specify the string in the 4th argument.

# Replace
substr($message, 2, 4, 'want to eat');

Substr function example program

This is an example to extract the string at the specified index using the substr function. In the following example, the string "Ken" is extracted.

# Extract the string at the specified index. The string to be extract is "Ken".
my $message = "I'm Ken";
my $name = substr($message, 4, 3);

This is an example that replaces the string at the specified index using the substr function.

# Replaces the string at the specified index. After the replacement, it becomes "I'm Mike".
my $message = "I'm Ken";
substr($message, 4, 3, 'Mike');

If you want to handle Unicode such as using Japanese

In order for the substr function to handle Unicode correctly, the string must be an decoded string. See the following articles for decoded strings.

Replace with regular expression

You can also replace strings using regular expression. If you want to specify the target string instead of the string index, use a regular expression.

# Replace Ken with Taro using a regular expression
my $message = "I'm Ken";
$message =~ s /Ken/Taro/;

Related Informatrion