2017-06-22 36 views
-3

我有以下输入存储在名为$ var1的单个标量变量中。如何使用perl将空格转换为新行?

输入(即存储在$ VAR1)

Gain Dead_coverage Export_control Functional_coverage Function_logic top dac_decoder Datapath System_Level Black_DV Sync_logic temp1 temp2 temp3 temp4 temp5 temp6 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 

预期输出:

Gain 
Dead_coverage 
Export_control 
Functional_coverage 
Function_logic 
top 
dac_decoder 
Datapath 
System_Level 
Black_DV 
Sync_logic 
temp1 
temp2 
temp3 
temp4 
temp5 
temp6 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 

我的代码:

我试过以下的正则表达式。

$var1=tr{\s}{\n}; 

上面的正则表达式不会带来我的预期输出。

注意:数字的范围可能高达n个数字,字符可能以大写或小写字母开头或结尾。无论我需要带来如预期的输出。对于那个正则表达式我可以使用它。

要求:

1.split space into new line. 
2.for numbers(i.e 123456789101112.....) it should be considered as follows 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
. 
. 
. 
so on,... 

After digit 9 the other numbers should be considered as double digit. 
+2

'tr'不能在Perl中使用正则表达式,但是/// g'却可以。 – toolic

+0

您输入的数字末尾没有空格。你如何期望最终在1,2,3,4等单独的行? – toolic

+0

即使我也不知道如何把它分开行@toolic – closedaccount

回答

1
tr

是音译。这只适用于个人角色,而不是模式。您需要使用s////g修饰符。

$var1 =~ s/\s/\n/g; 

您还可以splitjoin做到这一点。

$var1 = join "\n", split//, $var1; 

它不应该在性能方面的差异,即使有字符串很多

+1

'1234567891011121314151'在这种情况下不起作用。 – ssr1012

+0

@ ssr1012我没有看到。真正。但奇怪的输入。 – simbabque