[Perl] split函数的一个特殊点
时间:2007-12-30 来源:jarodwang
# get current PID of DB RACGIMON |
其中的split函数调用本来是写成:
$process = (split(/ /, $process))[1]; |
可是运行的时候确发现第2种写法并不能正确的取得PID。当时由于急着要用就没有仔细琢磨了,从了第1种写法,直到今天刚刚仔细看了《Programming Perl》中对split函数的讲解才弄明白了其中的区别。
其实,split函数的正规语法应该是:
split /PATTERN/, EXPR |
而第1种写法中使用单引号(或者双引号)来分隔空格(whitespace)实际上是一种特殊的例子:
As a special case, specifying a space " " will split on whitespace just as split with no arguments does. Thus, split(" ") can be used to emulate awk's default behavior, whereas split(/ /) will give you as many null initial fields as there are leading spaces. |
看了这段解释就明白了,原因就在于split(/ /, EXPR)会在碰到一个空格时就产生一个空(NULL)字段并将其加入到返回值列表中。
而偏偏在Linux上,ps -ef | grep "racgimon startd" | grep -v grep返回的结果中,用户名(oracle)和PID(15932)之间有2个空格(whitespace)!
为了验证书中的这个解释我写了下面这个脚本:
#! /usr/bin/perl |
而输出的结果是:
$first_token_0 is 15932 $first_token_1 is 15932 $first_token_2 is 15932 $first_token_3 is $first_token_4 is 15932 |
可以看到第2种写法(对应于$first_token_3)的内容为空(NULL)而不是PID(15932)了,要使用split(/ /, EXPR)的形式来正确地取得PID就得像$first_token_4那样。