use strict;
use warnings 'all';
sub trim(;$);
my $str=" a ,, ,two words ,,, b";
my @columns = map trim, split /,/, $str;
use Data::Dump;
dd \@columns;
sub trim(;$) {
(my $trimmed = $_[0] // $_) =~ s/\A\s+|\s+\z//g;
$trimmed;
}
一个很常见的解决方案是转换split返回的值。在这种情况下,你想删除任何前导或尾随空格,通常称为 trim 操作。使用这种方法,你根本不必担心split操作中的空格:
use strict;
use warnings;
my $str=" a, b, c>d:e, f, g ";
my @columns = map { s/^\s*|\s*$//gr } split(/,/, $str);
print join(',', @columns), "\n";
@toolic上面提到的另一个解决方案是事先删除所有空格:
use strict;
use warnings;
my $str=" a, b, c>d:e, f, g ";
$str =~ s/\s+//g; # remove all occurrences of 1 or more spaces
my @columns = split(/,/, $str);
print join(',', @columns), "\n";
2条答案
按热度按时间hsgswve41#
我建议您使用全局正则表达式匹配来查找所有既不是逗号也不是空格的字符子序列
它将生成与
split(/[\s\t,]+/
相同的输出。(注意,\t
是多余的,因为\s
也匹配制表符。)但是将创建一个没有任何空元素的列表输出
***请注意,***就像您的split一样,此方法将忽略任何空字段:类似
a,,,b
的语句将返回[ 'a', 'b' ]
而不是[ 'a', '', '', 'b' ]
。另外,包含空格的列将被拆分,因此a,two words,b
将生成[ 'a', 'two', 'words', 'b' ]
而不是[ 'a', 'two words', 'b' ]
。只有您才能判断是否可能出现这些情况如果此方法有可能产生错误的结果,则最好简单地按逗号拆分并编写子例程来修剪结果字段
输出
e0bqpujr2#
一个很常见的解决方案是转换split返回的值。在这种情况下,你想删除任何前导或尾随空格,通常称为 trim 操作。使用这种方法,你根本不必担心split操作中的空格:
@toolic上面提到的另一个解决方案是事先删除所有空格:
上述两种解决方案都返回以下输出:
a、B、c〉d:e、f、g
有关
/r
修饰符的详细信息:/r
是一个修饰符,可以应用于非破坏性的替换。这意味着原始字符串不被修改,而是创建、修改并返回。这有很多优点,因为通常在标量上下文中,s///
运算符将返回发生的替换次数,而不是修改后的字符串。这只在Perl版本〉= 5.14中可用。以下Perl版本的等效语句为:并在Map中使用:
例如: