【问题标题】:Learning Perl (Chapter 5.1) Issues学习 Perl(第 5.1 章)问题
【发布时间】:2020-08-26 23:10:52
【问题描述】:

我在使用“Learning Perl 6th Edition”第 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.

知道是什么导致了这个问题吗?

【问题讨论】:

  • 提示:运行cat I am the walrus - 这也不起作用。您应该将多行放入自己的文件中:cat text.txt./tac.pl text.txt
  • 我相信这本书在后面的几行中都有这一点……即在 ./tac.pl 之后按 RETURN
  • 当它使用文件作为参数时,它现在可以工作。正如 amon 以 cat 为例所示,当我需要使用文本文件时,我正在尝试错误地将命令行参数直接传递给程序。
  • Useless use of reverse in void context?行尾也有问题,因为perl 没有看到print。对 Perl 的 Windows 构建使用 CRLF,在其他地方使用 LF 结尾,包括 cygwin。

标签: perl


【解决方案1】:

命令行上的参数是行输入运算符读取的文件的名称。读取所有文件的所有行,并将其作为列表传递给reverse,然后将反向列表传递给print

创建这些文件:

弗雷德

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

在您的问题中,您向程序传递了参数,但它们不代表文件名。行输入操作符&lt;&gt; 没有可读取的内容,因为当没有文件存在时,使这项工作的魔法失败了。这就是奇怪的警告出现的地方。

如果您还有其他问题,请按照我刚刚向您展示的表格调整问题。显示输入文件以及程序的运行方式。祝你好运,:)

【讨论】:

    【解决方案2】:

    当您使用菱形运算符时,您正在以错误的方式运行程序。 当您以这种方式运行程序时,该程序期望找到名为“I”、“am”、“the”和“walrus”的文件。不带参数运行它,您将拥有一个从 STDIN 读取的程序。 我以为这本书在你读完之前就告诉你了。

    更多关于的信息可以在这里http://perldoc.perl.org/perlop.html(和其他地方)找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 2010-10-09
      相关资源
      最近更新 更多