Perl調用shell命令的幾大方法小結

來源:文萃谷 1.41W

一、system

Perl調用shell命令的幾大方法小結

perl也可以用system調用shell的命令,它和awk的system一樣,返回值也是它調用的命令的退出狀態.

複製代碼 代碼如下:

[root@AX3sp2 ~]# cat

#! /usr/bin/perl -w

$file = "";

system("ls -l ");

$result = system "ls -l $file";

print "$result n";#輸出命令的退出狀態

system "date";

[root@AX3sp2 ~]# perl

-rwxr-xr-x 1 root root 126 12-16 15:12

-rwxr-xr-x 1 root root 126 12-16 15:12

2010年 12月 16日 星期四 15:58:34 CST

二、反引號

perl的system函數和awk的一樣不能夠返回命令的`輸出.

要得到命令的輸出,就得使用和shell本身一樣的命令: ` `

複製代碼 代碼如下:

[root@AX3sp2 ~]# cat

#! /usr/bin/perl

print `date`;

print "this is test n";

[root@AX3sp2 ~]# perl

2010年 12月 16日 星期四 15:51:59 CST

this is test

三、exec

最後,perl還可以使用exec來調用shell的命令. exec和system差不多,不同之處在於,調用exec之後,perl馬上就退出,而不會去繼續執行剩下的代碼

複製代碼 代碼如下:

[root@AX3sp2 ~]# cat

#! /usr/bin/perl

exec ("echo this is test");

print "good bye !n";#這句話不會被輸出

[root@AX3sp2 ~]# perl

this is test

熱門標籤