文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>[Perl] split函数的一个特殊点

[Perl] split函数的一个特殊点

时间:2007-12-30  来源:jarodwang

上周在Linux上写了一个脚本来kill一个进程,其中取得进程对应的PID的一段代码如下:

# get current PID of DB RACGIMON
my $process = qx/$PSEF | $GREP "racgimon startd" | $GREP -v grep/;
$process = (split(' ', $process))[1];


其中的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

use strict;
use warnings;

my $sentence = "oracle  15932 1 0 Dec29 ? 00:00:08 /oracle/OraHome/bin/racgimon startd rac";

$_ = $sentence;

my $first_token_0 = (split)[1];

my $first_token_1 = (split(' ', $sentence))[1];

my $first_token_2 = (split(" ", $sentence))[1];

my $first_token_3 = (split(/ /, $sentence))[1];

my $first_token_4 = (split(/ /, $sentence))[2];

print "\$first_token_0 is $first_token_0\n";

print "\$first_token_1 is $first_token_1\n";

print "\$first_token_2 is $first_token_2\n";

print "\$first_token_3 is $first_token_3\n";

print "\$first_token_4 is $first_token_4\n";


而输出的结果是:

$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那样。
相关阅读 更多 +
排行榜 更多 +
打螺丝高手

打螺丝高手

模拟经营 下载
解救火柴人计划安卓版

解救火柴人计划安卓版

体育竞技 下载
鸡生化精英安卓版

鸡生化精英安卓版

飞行射击 下载