($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
獲取默認行爲,請傳遞單個文字空格字符作爲第一個參數。 不是一個正則表達式。文檔說這是
作爲另一種特殊情況,split模擬命令行工具awk的缺省行爲,當省略PATTERN或由單個空格字符組成的文字字符串(例如「'或」\ x20「,但沒有例如/ /)。在這種情況下,EXPR中的任何前導空白在分割之前被移除,而PATTERN被視爲/ \ s + /;特別是,這意味着任何連續的空格(不只是單個空格字符)都將用作分隔符。
請顯示您的輸入。 – Jean
這對我很好。 – Toto
你有領先的空白嗎?在'''上拆分將刪除它,然後在\ s +'上拆分 – RobEarl