我遇到'学习Perl第6版'第5章问题1的问题。
问题是要编写一个像cat一样的程序,但会反转输出行的顺序。
这本书给出了答案 打印反向<>;
我正在运行Perl v5.14.2
我的代码是:
#!/usr/bin/perl -w
print reverse <>;
在此之后,我在文件上运行chmod 755以确保它是可执行的。
在命令行上我正在尝试:
./tac.pl I am the walrus
我得到了这个回报:
Useless use of reverse in void context at ./tac.pl line 3.
Can't open I: No such file or directory at ./tac.pl line 3.
Can't open am: No such file or directory at ./tac.pl line 3.
Can't open the: No such file or directory at ./tac.pl line 3.
Can't open walrus: No such file or directory at ./tac.pl line 3.
Use of uninitialized value in reverse at ./tac.pl line 3.
知道是什么导致了这个问题吗?
答案 0 :(得分:1)
命令行上的参数是行输入操作符读取的文件的名称。读取所有文件的所有行,将其作为列表传递给reverse,并将反转列表传递给print。
创建这些文件:
<强> fred的强>
fred line one
fred line two
fred line three
<强>巴尼强>
barney line 1
barney line 2
barney line 3
barney line 4
<强>贝蒂强>
betty line a
betty line b
betty line c
当你捕捉这些时,你得到:
$ cat fred barney betty
fred line one
fred line two
fred line three
barney line 1
barney line 2
barney line 3
barney line 4
betty line a
betty line b
betty line c
现在,我们给出的Perl程序作为答案要求你改变它。 betty line c
应该是第一个,fred line one
应该是最后一个。当您按照编写程序运行程序时,您应该看到:
$ perl tac.pl fred barney betty
betty line c
betty line b
betty line a
barney line 4
barney line 3
barney line 2
barney line 1
fred line three
fred line two
fred line one
在您的问题中,您将参数传递给您的程序,但它们并不代表文件名。行输入操作符<>
没有任何东西可读,因为当没有文件存在时,使得该工作的魔力失败。这就是怪异警告的来源。
如果您还有其他问题,请在我刚刚向您展示的表单中调整问题。显示输入文件以及程序的运行方式。祝你好运,:))
答案 1 :(得分:0)
使用钻石操作符时,您正在以错误的方式运行程序。 当你以这种方式运行时,程序希望找到名为“I”,“am”,“the”和“walrus”的文件。不带参数运行它,你将有一个从STDIN读取的程序。 在你深入了解之前,我以为这本书告诉过你。
有关&lt;&gt;的更多信息可以在http://perldoc.perl.org/perlop.html(以及其他地方)找到。