为什么“学习Perl第6版”的这个例子不会运行?

时间:2011-09-12 06:15:56

标签: perl

我被困在Learning Perl第6版的第2章练习2第42页。 我从第296页复制了问题的代码示例。我在Ubuntu 11.04上使用Perl版本5.10.1。我得到的错误,我无法弄清楚有人可以帮忙吗?我将列出下面的代码和错误消息。

#!/usr/bin/perl -w
$pi = 3.141592654;
print "What is the radius? ";
chomp($radius = <STDIN>);
$circ = 2 * $pi * $radius;
print "The circumference of a circle of radius $radius is $circ.\n";

我得到的错误是:

./ex2-2: line 3: =: command not found
Warning: unknown mime-type for "What is the radius? " -- using "application/octet-stream"
Error: no such file "What is the radius? "
./ex2-2: line 5: syntax error near unexpected token `$radius'
./ex2-2: line 5: `chomp($radius = <STDIN>);'

2 个答案:

答案 0 :(得分:9)

您正在使用shell而不是perl执行Perl脚本。基于行数偏离1的事实,我怀疑问题的原因是在shebang(#!)行之前的空白行。 #!必须是文件的前两个字节。删除此空白行。

如果那不是问题,那么也许您使用

执行了脚本
. ex2-2

sh ex2-2

何时应该使用

perl ex2-2

ex2-2       # if "." is in your $PATH

./ex2-2

最后两个要求您使脚本可执行(chmod u+x ex2-2)。

答案 1 :(得分:4)

如果您复制并粘贴了您执行的内容,将会有所帮助。请注意,以下示例中的行号不同:

$ cat x.pl
#!/usr/bin/perl -w
$pi = 3.141592654;
print "What is the radius? ";
chomp($radius = <STDIN>);
$circ = 2 * $pi * $radius;
print "The circumference of a circle of radius $radius is $circ.\n";
$ sh x.pl
x.pl: line 2: =: command not found
x.pl: line 3: print: command not found
x.pl: line 4: syntax error near unexpected token `$radius'
x.pl: line 4: `chomp($radius = <STDIN>);'
$

这是在MacOS X 10.7.1上使用Bash 3.x。

鉴于输出,我可以自信地诊断出您的脚本是作为shell脚本运行而不是作为Perl脚本运行; bash用于运行它。