- Perl 6 Deep Dive
- Andrew Shitov
- 126字
- 2021-07-03 00:05:53
Methods to cut strings
The two methods—chop and chomp—have similar names but have a different sensitivity to the characters they work with. The chop method cuts out the last character of the string. The chomp method only cuts the last character if it is a newline character.
say "Text\n".chomp; # Text
say "Text\n".chop; # Text
say "Text".chomp; # Text
say "Text".chop; # Tex
Another group of methods—trim, trim-leading, and trim-trailing—cuts the spaces at the beginning and/or end of the string. Consider the following code snippet:
my $s = ' word '.trim;
say "[$s]"; # [word]
$s = ' word '.trim-leading;
say "[$s]"; # [word ]
$s = ' word '.trim-trailing;
say "[$s]"; # [ word]