我想在Perl中转换shell脚本代码,并使用exec执行代码。我有用perl编写的程序,但在一定条件下,我必须添加一个代码,该代码我知道我们可以在shell脚本中执行的操作,但不确定如何在perl中执行。
Shell脚本代码:
(
echo "MIME-Version: 1.0"
echo "Subject: "
echo "Content-Type: text/html"
cat <emailbody>
) | mailx -r "test@gmail.com"
我的Perl代码:
!/usr/bin/perl
use strict;
use warnings;
my $mailx = "/usr/bin/mailx";
if($ARGV[0] eq "ty" && $ARG[1]){
/// Here we want to use the shell script code .
}
my @args_to_pass = ($mailx, @ARGV);
exec @args_to_pass;
答案 0 :(得分:3)
您的shell代码的字面翻译为:
DispatchQueue.global(qos: .default).async {
while true {
self.mouseLoc = NSEvent.mouseLocation
if self.mouseLoc == self.storeMouseLoc {continue}
Thread.sleep(forTimeInterval: 0.1)
self.storeMouseLoc = self.mouseLoc
// I can do lots of useful thing here .....
}
}
这个想法是创建一个管道和一个子过程。如上所示,使用open
可以做到这一点,管道的写端连接到子级的if($ARGV[0] eq "ty" && $ARG[1]){
my $pid = open(STDIN, '-|') // die "Can't fork(): $!";
if ($pid == 0) {
print "MIME-Version: 1.0\n";
print "Subject: \n";
print "Content-Type: text/html\n";
exec 'cat', ... or die "Can't exec() cat: $!";
# or print more text, but don't forget to exit() afterwards if you don't exec
}
}
,读端连接到父级的STDOUT
。
然后,子进程将数据写入管道并退出。它可以自己完成所有工作,也可以STDIN
或最后将exit
放入exec
。
孩子产生的所有输出都可以在父母的cat
上获得,STDIN
继承了该知识。