[英]How can I make split(/\t/, $STRING) detect empty values when $STRING ends with “\t\t”?
How can I make split(/\\t/, $STRING)
detect empty items when $STRING
ends with "\\t\\t"
? 当
$STRING
以"\\t\\t"
结尾时split(/\\t/, $STRING)
如何进行split(/\\t/, $STRING)
检测空项目?
Using Perl script, I am trying to split strings based on as a separator between items then count and use these items. 使用Perl脚本,我试图基于作为项之间的分隔符来拆分字符串,然后计算并使用这些项。 But, when the strings end with a combination s, the script doesn't count empty items.
但是,当字符串以组合s结束时,脚本不会计算空项。
Example: 例:
string="value1\\tvalue2\\t\\t\\t\\t"
(value1, value2 and 4 empty items) string="value1\\tvalue2\\t\\t\\t\\t"
(value1,value2和4个空项)
but it counts 2 items (value1, value2): 但它有2个项目(value1,value2):
$STRING="value1\tvalue2\t\t\t\t";
print $STRING."\n";
my @F = split(/\t/, $STRING);
print scalar(@F)."\n";
# The number of items must match the number of header name
if( scalar(@F) == 6 )
{
print "Done \n";
}
the code prints: 代码打印:
value1 value2
2
while what is expected is: 而预期的是:
value1 value2
6
Change the split
line by adding -1
as a parameter: 通过添加
-1
作为参数来更改split
线:
my @F = split(/\t/, $STRING, -1);
Output: 输出:
value1 value2
6
Done
Per perldoc split
, the parameters to split
are PATTERN, EXPR, LIMIT
. 每
perldoc split
,要split
的参数是PATTERN, EXPR, LIMIT
。 In your current situation, "LIMIT is omitted so "trailing empty fields are stripped." 在你目前的情况下,“LIMIT被省略,所以”尾随空字段被剥离。“
By adding the -1
value for LIMIT
: 通过为
LIMIT
添加-1
值:
If LIMIT is negative, it is treated as if it were instead arbitrarily large;
如果LIMIT为负数,则将其视为任意大; as many fields as possible are produced.
生成尽可能多的字段。
So a negative final argument prevents split
from discarding trailing fields. 因此,否定的最终参数可防止
split
废弃尾随字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.