當前位置:才華齋>範例>工作總結>

Perl呼叫shell命令的幾大方法小結

工作總結 閱讀(1.49W)

一、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