提示信息

Perl调用shell命令方法小结

峰子 已关注

一、system

perl也可以用system调用shell的命令,它和awk的system一样,返回值也是它调用的命令的退出状态.

  1. [root@mycoding ~]# cat aa.pl
  2. #! /usr/bin/perl -w
  3. $file = "wt.pl";
  4. system("ls -l wt.pl");
  5. $result = system "ls -l $file";
  6. print "$result \n"; #输出命令的退出状态
  7. system "date";
  8. [root@mycoding ~]# perl aa.pl
  9. -rwxr-xr-x 1 root root 126 12-16 15:12 wt.pl
  10. -rwxr-xr-x 1 root root 126 12-16 15:12 wt.pl
  11. 2010年 12月 16日 星期四 15:58:34 CST

二、反引号

perl的system函数和awk的一样不能够返回命令的输出. 要得到命令的输出,就得使用和shell本身一样的命令: ``

  1. [root@mycoding ~]# cat bb.pl
  2. #! /usr/bin/perl
  3. print `date`;
  4. print "this is test \n";
  5. [root@mycoding ~]# perl bb.pl
  6. 2010年 12月 16日 星期四 15:51:59 CST
  7. this is test

三、exec

最后,perl还可以使用exec来调用shell的命令. exec和system差不多,不同之处在于,调用exec之后,perl马上就退出,而不会去继续执行剩下的代码

  1. [root@mycoding ~]# cat cc.pl
  2. #! /usr/bin/perl
  3. exec ("echo this is test");
  4. print "good bye !\n"; #这句话不会被输出
  5. [root@mycoding ~]# perl cc.pl
  6. this is test
    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
峰子 关注 已关注

最近一次登录:2019-10-10 14:28:58   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图