两段代码,第二段比较好些。
下面是Split输出结果方式的代码:
#!/usr/local/bin/perl #Date:2015-07-07 print "Begin to restart tomcat "; my $output = `ps -ef|grep tomcat`; print "$output "; my $pid="-1"; my @arr=split(/ /,$output); $length=@arr; $index=0; while($index<$length){ $line=$arr[$index]; my @arrLine=split(/s+/,$line); if($arrLine[0] eq "root" && $arrLine[2] eq "1" && $arrLine[3] eq "99"){ $pid=$arrLine[1]; print "Found tomcat's pid=$pid "; } $index++; } if($pid eq "-1"){ print "No tomcat run,will start it "; system("/home/rtt8/apache-tomcat-7.0.42/bin/startup.sh"); print "Tomcat was started "; }else{ system("kill -9 $pid"); print "Tomcat was killed "; system("/home/rtt8/apache-tomcat-7.0.42/bin/startup.sh"); print "Tomcat have been restarted "; }
下面是正则表达式查找输出结果的代码
#!/usr/local/bin/perl #Date:2015-07-07 print "1.Find running tomcat "; my $output = `ps -ef|grep tomcat`; print "$output "; if($output=~/(root)s+(d+)s+(1)s+(99)/){ $pid=$2; print "Found running tomcat's pid=$pid "; system("kill -9 $pid"); print "Running tomcat was killed "; }else{ print "No running tomcat,will start it "; } print " 2.Start tomcat "; system("/home/rtt8/apache-tomcat-7.0.42/bin/startup.sh"); print "Tomcat was started. ";