美文网首页
从例子学习Perl的system函数

从例子学习Perl的system函数

作者: zczhuohuo | 来源:发表于2015-12-18 23:45 被阅读5870次

从例子学习Perl的system函数

例子1

避免:
system("chown $user.sgd newdata.txt");
推荐:
system("/usr/bin/chown $user:sgd newdata.txt");
system("/usr/ucb/chown $user.sgd newdata.txt");

理由:如果不是绝对路径,那么不同的用户执行脚本的时候,由于环境不一样,命令可能不一样。此外,由于没有指定绝对路径,会有安全隐患。

例子2

避免:
if (!system("$sub_script $user $file")) {
    print "success!\n";
}
推荐:
if (system("$sub_script $user $file") == 0) {
    print "success!\n";
}

理由:system函数的返回值低8位存Unix Signal,高位存命令执行的返回值,因此,如果需要判断shell命令是否执行成功,必须判断返回的值是否为0.

例子3

避免:
system("rm $dir/orf_geneontology.tmp");
system "mkdir $tempDir";
system("/bin/kill -HUP $pid");
推荐:
unlink("$dir/orf_geneontology.tmp");
mkdir $tempDir;
$number_killed = kill('HUP', $pid);

理由:尽量使用Perl内置的函数。

例子4

推荐:
open(PS, "/usr/bin/ps -aux |");
while (<PS>) { print } # process the output of ps command one line at a time
close(PS);
This is generally preferable to creating a temporary file with the output and reading it back in:
避免:
my $temporary_file = "/tmp/ps_output$$";
system("/usr/bin/ps -aux > $temporary_file");
open(PS, $temporary_file);
while (<PS>) { print } # process the output of ps command one line at a time
close(PS);
unlink($temporary_file);

理由:第一种写法更加简洁,更加Perl!

exec函数从来不返回(相当于重新执行了一个新的程序),因此很少使用。

相关文章

  • 从例子学习Perl的system函数

    从例子学习Perl的system函数 例子1 理由:如果不是绝对路径,那么不同的用户执行脚本的时候,由于环境不一样...

  • Learning Perl 学习笔记 Ch16 进程管理

    在Perl中调用其他程序的方式有很多,最简单的就是system函数,system函数接受一个或多个参数,其中第一个...

  • PvZ2 破解版自动抽奖

    perl -e "while(1){system('adb shell input tap 750 1040');...

  • RepeatMasker的安装和使用

    Install RepeatMasker 安装前的准备 Unix system with perl 5.8.0 o...

  • 子程序

    perl中的子模块是一种函数,就是用户自定义的函数,函数包括子函数和内置函数。 perl中的函数的特点就是自带返回...

  • Perl子程序(函数)和引用

    Perl子程序(函数) Perl子程序也就是用户自定义的函数 Perl子程序可以出现在程序的任何地方,语法格式如下...

  • perl函数

    1. 计算两个日期之间相差天数 转换成秒计算 2. 一个字符串里的某一段字符,替换成另一端字符串里的字符

  • Perl基础系列合集

    ​Perl学习01之标量数据 Perl学习02数组和哈希使用 Perl学习03之流程控制结构 Perl学习04之I...

  • 第五章 Perl函数

    Perl中,函数(又称子程序)是一个封装的行为单元。函数可以有自己的名字,可以接受输入,可以产生输出,它是Perl...

  • system() 函数

    system("dir /a / b >>name.txt");

网友评论

      本文标题:从例子学习Perl的system函数

      本文链接:https://www.haomeiwen.com/subject/qqgphttx.html