0

如何使用 Perl 创建另一个名为hello.sh?

我试过:

#*perl codes*
#Before this has perl's section of codes
#Now want to create shell script
open FILE , ">hello.sh" or die $!;
chmod 0755, "hello.sh";
print FILE
"#!/bin/sh
echo "Hello World!
";
close FILE;

但这是相当多余的。如果我想使用 IF-ELSE,这将很难做到。

任何的想法?

编辑

我试过这个

print FILE
"#!/bin/sh
if [-d $1]; then
echo "It's a directory at $(pwd)"
else
echo $1 is not a directory
fi
";

如您所见,Its检测不是字符串,我在这里错过了任何语法吗?

4

3 回答 3

3

您应该将内容打印到文件句柄FILE

open FILE , ">", "hello.sh" or die $!;
chmod 0755, "hello.sh";

print FILE <<'END';
#!/bin/sh
echo "Hello World!"
END

close FILE;

<<'END' ..是 heredoc 语法,它不会尝试插入 perl 将识别为变量的字符串(以$or为前缀@

它还确保'or"引号不需要转义\

于 2013-05-29T16:36:15.853 回答
1

您需要转义引号:

print FILE '#!/bin/sh
if [-d $1]; then
echo "It\'s a directory at $(pwd)"
else
echo $1 is not a directory
fi
';

或使用q

print FILE q{#!/bin/sh
if [-d $1]; then
echo "It's a directory at $(pwd)"
else
echo $1 is not a directory
fi
};

或者一个heredoc:

print FILE <<'OUT';
#!/bin/sh
if [-d $1]; then
echo "It's a directory at $(pwd)"
else
echo $1 is not a directory
fi
OUT
于 2013-05-29T17:01:46.147 回答
0

这有效:

open FILE , ">hello.sh" or die $!;
chmod 0755, "hello.sh";
print FILE "#!/bin/sh
echo Hello World!
";
close FILE;
于 2013-05-29T16:32:38.063 回答