How to remove the last character of a string in Perl
Overview
We can use the chop() method to remove the last character of a string in Perl. This method removes the last character present in a string. It returns the character that is removed from the string, as the return value.
Syntax
chop(str)
Parameters
str: This is the string whose last character we want to remove.
Return value
The value returned is the last character that is removed from the string.
Code example
# create strings$string1 = "Educative is the best";$string2 = "Perl language is interesting";$string3 = "Perl developer";# remove last strings$r1 = chop($string1);$r2 = chop($string2);$r3 = chop($string3);# print removed charactersprint "$r1\n";print "$r2\n";print "$r3\n";# print stringsprint "$string1\n";print "$string2\n";print "$string3\n";
Code explanation
- Lines 2–4: We create the string values.
- Lines 7–9: We invoke the
chop()method on the strings we created, and then we store the results in the variables$r1,$r2, and$r3. - Lines 12–14: We print the characters that were removed, using the
chop()method, to the console. - Lines 17–19: We print the modified strings to the console.