如何使用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
检测不是字符串,
我在这里错过了任何语法吗?
答案 0 :(得分: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会识别为变量的字符串(前缀为$
或@
)
它还确保不需要使用'
"
或\
引号
答案 1 :(得分: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
答案 2 :(得分:0)
这有效:
open FILE , ">hello.sh" or die $!;
chmod 0755, "hello.sh";
print FILE "#!/bin/sh
echo Hello World!
";
close FILE;