我已经浏览了很多教程,但我仍然无法弄清楚我做错了什么..我正在尝试下面的代码(在.pl Perl文件中,作为可执行文件):
#!/usr/bin/perl
perl -e 'print "Hello";'
我运行此脚本并获取:
/home/user1/Desktop/file_backups.pl的执行因编译错误而中止。
(我是使用Perl调用Linux命令行的新手。)
答案 0 :(得分:15)
尝试:
#!/usr/bin/perl
# This is a comment ~~~
# This script will be run as a Perl script
# since 'perl' isn't a keyword or function in Perl
# something like this must fail:
#
# perl -e 'print "Hello";'
#
# The following should work.
print "Hello"; print " World\n";
或者,如果您希望shell脚本执行Perl代码:
#!/bin/sh
# That's a Bash script ~~~
# It's just a command line in a file ...
perl -e 'print "Hello World";'
背景:#!
是interpreter directive。
执行命令时,它将转换为执行解释器。
答案 1 :(得分:12)
perl
不是Perl脚本中的有效命令。如果您将该文件命名为.sh脚本,并在shebang行上使用#!/bin/bash
,那么它就可以工作了,但编写一个bash文件只是为了调用Perl并不是很有意义(为什么不直接调用Perl?)
由于您提到要与命令行进行交互,因此我在此提及您可以通过@ARGV
数组获取Perl中的命令行选项。 (见perldoc perlvar。)
答案 2 :(得分:10)
只需在命令行输入(不在文件中)
perl -e 'print "Hello World\n";'
这对oneliners来说真的很好。较长的脚本需要自己的文件...
答案 3 :(得分:4)
这应该有效。在单引号内加双引号;)
perl -e "print 'Hello'"
答案 4 :(得分:0)
您可能正在尝试这样做:
system("/usr/bin/perl -e 'print \"Hello!\\\\n\";'");
答案 5 :(得分:0)
既然你说你正在寻找相反的观点,那么这可能是你的意思:
# vi stdin.pl
# cat stdin.pl
#!/usr/bin/perl
while(<STDIN>)
{
if( /^hello/ ){ print "Hello back to ya!\n"; }
}
# chmod 0777 stdin.pl
# ./stdin.pl
foo
hello
Hello back to ya!
#
答案 6 :(得分:0)
假设您有以下输入:
$ for i in a b c ; do echo "$i is $i" > $i; done $ cat a b c a is a b is b c is c
每个人都知道大写字母很多更好!
perl -i.bak -pe '$_ = uc' a b c
所以现在
$ cat a b c A IS A B IS B C IS C
但是我们真的很想在名为upcase
的命令中做到这一点,这很容易做到!
#! /usr/bin/perl -pi.bak
$_ = uc
在工作中看到它:
$ for i in a b c ; do echo "$i is $i" > $i; done $ cat a b c a is a b is b c is c $ ./upcase a b c $ !cat cat a b c A IS A B IS B C IS C
来自answer to a similar question的更多提示:
-e
选项引入了要执行的Perl代码 - 您可能会将其视为命令行上的脚本 - 因此将其删除并将代码粘贴在正文中。将-p
留在shebang(#!
)行。一般来说,最安全的做法是坚持shebang系列中最多一个“丛”选项。如果你需要更多,你总是可以将它们的等价物扔进
BEGIN {}
块。不要忘记打开执行位!
chmod +x script-name
因为你没有给出你想转换的实际单行,我不得不给出一个广泛的,一般的答案。如果您编辑问题以使其特定于您想要做的事情,我们可以提供更多有用的答案。