It's best to use the end-of-string or end-of-line metacharacters which solves the problem of not getting rid of the spaces between "Last" and "Known".
The dollar-sign $ character means end of line or end of string if the string has only one line.
The \s means a space so you don't need a physical space " "
It's also probably better to use s/// (substitution) rather than tr/// (tranliteration) although either should work.
s/\s*$//; # means substitute zero or more spaces
# before end-of-line with NOTHING (get rid of them)
Here's some basic sample code:$jo = "Mary had a little lamb ";
print $jo . "blah\n";
$jo =~ s/\s*$//; # get rid of the spaces
print $jo . "blah\n";
Here's the output:Mary had a little lamb blah # spaces at end of $jo
Mary had a little lambblah # spaces be gone!
---------------------------------------------------------
There's also the \z character which means end of string, no matter what (ragardless of any newlines).
\Z matches anything right before a newline at the end of a string or the end of a string if there is no newline.
The $ character is pretty much the same as \Z unless the string has several newlines (string is a paragraph) and then the $ would match before a newline character, not necessarily the end of the string.
Therefore, if you have a paragraph and want to get rid of spaces at the end of EVERY line, you could do something like: s/\s*$//gm;
The /g applies the substitution to multiple matches, while /m tells Perl that there are Multiple lines (as opposed to /s Single line)
\A and ^ are the same as \Z and $ but in the begging of a line or a string - hey, A is the first and Z is the last letter of the alphabet :)
If you're not too familiar with regular expressions, you should read up on the different metacharacters you can you (don't lose your marbles, though - it can get hectic) |