chop

chopVARIABLEchopLISTchop
This function chops off the last character of a string variable
and returns the character chopped. The chop function is used primarily to remove the
newline from the end of an input record, and it is more efficient than
using a substitution. If that’s all you’re doing, then it would be safer
to use chomp, since chop always shortens the string no matter
what’s there, and chomp is more
selective.
You cannot chop a literal, only
a variable. If you chop a
LIST of variables, each string in the list is
chopped:
@lines = `cat myfile`; chop @lines;
You can chop anything that is
an lvalue, including an assignment:
chop($cwd = `pwd`); chop($answer = <STDIN>);
This is different from:
$answer = chop($tmp = <STDIN>); # WRONG
which puts a newline into $answer because chop returns the character chopped, not the
remaining string (which is in $tmp).
One way to get the result intended here is with substr:
$answer = substr <STDIN>, 0, –1;
But this is more commonly written as:
chop($answer = <STDIN>);
In the most general case, chop
can be expressed using substr:
$last_char = chop($var); $last_char = substr($var, –1, 1, ""); # same thing
Once you understand this equivalence, you can use it to do bigger
chops. To chop more than one character, use substr as an lvalue, assigning a null ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access