为了回应@Ted Hopp的评论,我决定看看我是否可以在保留空白的同时做到这一点。我还对如何处理删除的单词之前和之后的空白做出了条件。是的,这是过度杀伤力,但我拖延做其他事情。
#!/usr/bin/perl
use strict;
use warnings;
my $word_to_remove = 3;
my $remove_leading_space = 0;
my $remove_trailing_space = 1;
while(my $in_string = <DATA>) {
chomp $in_string;
my @fields = split(/(\s+)/, $in_string);
my $field_to_remove = 2*$word_to_remove - 2;
#back up the splice position if removing leading space
$field_to_remove -= ($remove_leading_space) ? 1 : 0;
#move forward if there are is a leading portion of whitespace
$field_to_remove += ($fields[0] eq '') ? 2 : 0;
my $total_to_remove =
1 +
(($remove_leading_space) ? 1 : 0) +
(($remove_trailing_space) ? 1 : 0);
splice(@fields, $field_to_remove, $total_to_remove);
my $out_string = join('', @fields);
print $out_string . "\n";
}
__DATA__
one two four five
one two four five
one two four five
定义“单词”:是否在单词之前/之后包含标点符号? – 2011-03-15 07:34:27