($red, $tapinfo) = split(/:/, $line);
@fields = split(/\s+/, $tapinfo);
在数组字段中,我看到甚至添加了空间。我想消除空格,以便字段只包含非空格字符。请评论可能出了什么问题。
($red, $tapinfo) = split(/:/, $line);
@fields = split(/\s+/, $tapinfo);
在数组字段中,我看到甚至添加了空间。我想消除空格,以便字段只包含非空格字符。请评论可能出了什么问题。
我假设您正在谈论剩余的前导空格,因此@fields
看起来像:
$VAR1 = [
'', # empty field
'foo',
'bar'
];
这是因为当/\s+/
您split
应该使用默认值' '
(单个空格字符)时,您正在使用。此默认行为将在拆分字符串之前去除前导空格。换句话说,你应该这样做:
@fields = split(' ', $tapinfo);
这记录在perldoc -f split中:
As another special case, "split" emulates the default behavior
of the command line tool awk when the PATTERN is either omitted
or a *literal string* composed of a single space character (such
as ' ' or "\x20", but not e.g. "/ /"). In this case, any leading
whitespace in EXPR is removed before splitting occurs, and the
PATTERN is instead treated as if it were "/\s+/"; in particular,
this means that *any* contiguous whitespace (not just a single
space character) is used as a separator. However, this special
treatment can be avoided by specifying the pattern "/ /" instead
of the string " ", thereby allowing only a single space
character to be a separator.
默认split
情况下与
my @list = $string =~ /\S+/g;
即它找到所有非空白字符的连续子串。
您可以使用正则表达式,但要从中获取默认行为split
,请将单个文字空格字符作为第一个参数传递。不是正则表达式。文档说这个
作为另一种特殊情况,当 PATTERN 被省略或由单个空格字符组成的文字字符串(例如 ' ' 或 "\x20" ,但不是例如 // )时, split 模拟命令行工具 awk 的默认行为。在这种情况下,EXPR 中的任何前导空格在拆分发生之前都会被删除,而 PATTERN 则被视为 /\s+/ ;特别是,这意味着任何连续的空格(不仅仅是单个空格字符)都用作分隔符。