Perl Newbies

  1. Perl
  2. Functions
  3. here

substr function - Extraction and replacement of substring

substr function extracts or replaces substring at specific position and length. The first argument is a string, the second argument is the start position, and the third argument is the length to be extracted. The starting position starts from 0. If the third argument is omitted, Until end of string is range.

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

To replace a substring at the specific position, specify a string for replacement in the fourth argument.

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

substr function programming example

This is an example that uses substr function to extract substring at the specific position.

# Extract substring at the specific position. Extracted substring is "Ken".
my $message = "I'm Ken";
my $name = substr($message, 4, 3);

This is an example to replace a string at a specific position using the substr function.

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

If you want to handle Multi bytes string such as Japanese

In order to handle Multi bytes string such as Japanese correctly in the substr function, the string must be an decoded string. To know decoded string, see the following article.

Replace with regular expression

You can also replace string using regular expression. If you want to specify string instead of start position, use a regular expression.

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