我在文件中有多个字符串,每行一个字符串:
[random string] was [failed/passed] 1y 2mo 3d 1h 51m 2s ago [some string]
现在我要做的是用6个变量(年,月,日,小时,分钟,秒)提取持续时间,以计算具有“日期”功能的日期。 我还希望在变量中获得通过/失败(例如O / 1)。
我遇到了3个问题:
如果我设法读取一个字符串,我尝试用剪切解析它,但我不知道如何摆脱字母(y,mo,h ...)并且只保留号。
持续时间格式是可变的;它可以是不到一年的1mo 2h 3s,或1y 3d 58m 3s,或3h 5s ......等等。我不知道如何处理这种变化。我猜这个命令必须检查字母并分配功能,并将0分配给不存在的字母。
非常感谢你的帮助!
答案 0 :(得分:1)
以下是我认为适合您的perl
代码。
#!/usr/bin/perl
my $string = <STDIN>;
chomp $userword; # Get rid of newline character at the end
@arr = $string =~ /(passed|failed).+?([\d]+[yY].)?([\d]+(?:mo|MO).)?([\d]+[dD].)?([\d]+[hH].)?([\d]+[mM].)?([\d]+[sS])/g;
$arr_len = scalar @arr;
print "Result: $arr[0]\n";
for($i=1;$i<=$arr_len;$i=$i+1){
$arr[$i]=~/(\d+)([A-Za-z]*)/g;
if ( $2 eq "y" | $2 eq "Y" ) {
print "Year is $1\n";
} elsif ( $2 eq "mo" | $2 eq "MO") {
print "Month is $1\n";
} elsif ( $2 eq "d" | $2 eq "D") {
print "Day is $1\n";
} elsif ( $2 eq "h" | $2 eq "H") {
print "Hour is $1\n";
} elsif ( $2 eq "m" | $2 eq "M") {
print "Minute is $1\n";
} elsif ( $2 eq "s" | $2 eq "S" ) {
print "Second is $1\n";
}
}
我尝试了三种不同的输入,它们是:
[random string] was failed 1y 2mo 3d 1h 51m 2s ago [some string]
[random string] was passed 2mo 3d 1h 51m 2s ago [some string]
asd sd asdg s passed 1y 2mo 3d 1h 2s
[random string] was failed 1y 4d 5h 3m 2s ago [some string]
相应显示所有三个的输出:
Result: failed
Year is 1
Month is 2
Day is 3
Hour is 1
Minute is 51
Second is 2
Result: passed
Month is 2
Day is 3
Hour is 1
Minute is 51
Second is 2
Result: passed
Year is 1
Month is 2
Day is 3
Hour is 1
Second is 2
Result: failed
Year is 1
Day is 4
Hour is 5
Minute is 3
Second is 2
以下是一些事情:
switch
,因为它可能会出错Can't locate Switch.pm in @INC (you may need to install the Switch module)
perl
编程。如果有人找到改进代码的方法,请建议我。我将非常感激。