简体   繁体   English

使用 perl 打印文本文件

[英]Printing a text file using perl

I am completely new to this and this should be the easiest thing to do but for some reason I cannot get my local text file to print.我对此完全陌生,这应该是最简单的事情,但由于某种原因,我无法打印本地文本文件。 After trying multiple times with different code I came to use the following code but it doesn't print.使用不同的代码多次尝试后,我开始使用以下代码,但它没有打印出来。

I have searched for days on various threads to solve this and have had no luck.我已经在各种线程上搜索了几天来解决这个问题,但没有运气。 Please help.请帮忙。 Here is my code:这是我的代码:

#!/usr/bin/perl

$newfile = "file.txt";
open (FH, $newfile);

while ($file = <FH>) {
         print $file;
}

I updated my code to the following:我将代码更新为以下内容:

#!/user/bin/perl

use strict;            # Always use strict
use warnings;          # Always use warnings.

open(my $fh, "<", "file.txt") or die "unable to open file.txt: $!";
                   # Above we open file using 3 handle method
                   # or die die with error if unable to open it.
while (<$fh>) {        # While in the file.
     print $_;     # Print each line
 }
close $fh;             # Close the file

system('C:\Users\RSS\file.txt');

It returns the following: my first report generated by perl.它返回以下内容:我由 perl 生成的第一个报告。 I do not know where this is coming from.我不知道这是从哪里来的。 Nowhere do I have a print "my first report generated by perl.";我在任何地方都没有打印“我的第一份报告由 perl 生成。”; statement and it definitely is not in my text file.声明,它绝对不在我的文本文件中。

My text file is full of various emails, addresses, phone numbers and snippets of emails.我的文本文件充满了各种电子邮件、地址、电话号码和电子邮件片段。

Thank you all for your help.谢谢大家的帮助。 I figured out my problem.我想出了我的问题。 I somehow managed to kick myself out of my directory and did not realize it.我不知何故设法将自己踢出我的目录,但没有意识到这一点。

This is most likely a combination of a failure to open the file, and a failure to check the return value of open .这很可能是打开文件失败和检查open返回值失败的组合。

If you are completely new to perl, I warmly recommend reading the excellent "perlintro" man page, using either man perlintro or perldoc perlintro on the command line, or taking a look here: https://perldoc.perl.org/perlintro.html .如果您完全不熟悉 perl,我强烈建议您阅读优秀的“perlintro”手册页,在命令行上使用man perlintroperldoc perlintro ,或查看此处: https : perldoc perlintro 。 .html

The "Files and I/O" section there gives a good and concise way of doing this:那里的“文件和 I/O”部分提供了一种很好且简洁的方法:

open(my $in,  "<",  "input.txt")  or die "Can't open input.txt: $!";

while (<$in>) {     # assigns each line in turn to $_
     print "Just read in this line: $_";
}

This version will give you an explanation and abort if anything goes wrong while trying to open the file.如果在尝试打开文件时出现任何问题,此版本将为您提供解释并中止。 For example, if there is no file named file.txt in the current working directory, your version will quietly fail to open the file, and afterwards it will quietly fail to read from the closed file handle.例如,如果当前工作目录中没有名为file.txt文件,则您的版本将悄悄地无法打开该文件,之后它将悄悄地无法从关闭的文件句柄中读取。

Also, always adding at least one of these to your perl scripts will save you a lot of trouble in the long run:此外,从长远来看,始终将其中至少一个添加到您的 perl 脚本中将为您节省很多麻烦:

use warnings; # or use the -w command line switch to turn warnings on globally
use diagnostics;

These won't catch the failure to open the file, but will alert on the failed read.这些不会捕获打开文件的失败,但会在读取失败时发出警报。

In the first example here you can see that without the diagnostics module, the code fails without any error messages.在此处的第一个示例中,您可以看到,如果没有诊断模块,代码将失败且没有任何错误消息。 The second example shows how the diagnostics module changes this.第二个示例显示了诊断模块如何改变这一点。

$ perl -le 'open FH, "nonexistent.txt"; while(<FH>){print "foo"}'
$ perl -le 'use diagnostics; open FH, "nonexistent.txt"; while(<FH>){print "foo"}'
readline() on closed filehandle FH at -e line 1 (#1)
    (W closed) The filehandle you're reading from got itself closed sometime
    before now.  Check your control flow.

By the way, the legendary "Camel Book" is basically the perl man pages formatted for paper printing, so reading the perldocs in the order listed in perldoc perl will give you a high level of understanding of the language in a reasonably accessible and inexpensive manner.顺便说一句,传说中的“骆驼书”基本上是为纸张打印而格式化的 perl 手册页,因此按照perldoc perl列出的顺序阅读 perldocs 将使您以合理可访问且廉价的方式对该语言有高度的理解.

Happy hacking!快乐黑客!

This is simple and including explanations.这很简单,包括解释。

use strict;            # Always use strict
use warnings;          # Always use warnings.

open(my $fh, "<", "file.txt") or die "unable to open file.txt: $!";
                       # Above we open file using 3 handle method
                       # or die die with error if unable to open it.
while (<$fh>) {        # While in the file.
         print $_;     # Print each line
 }
close $fh;             # Close the file

There is then also the case where you are trying to open a file which is not in a location where you think it is.还有一种情况是,您尝试打开的文件不在您认为的位置。 So consider doing full path, if not in the same dir.所以考虑做完整路径,如果不在同一个目录中。

open(my $fh, "<", 'F:\Workdir\file.txt') or die "unable to open < input.txt: $!"; 

EDIT: After your comments, it seems that you are opening an empty file.编辑:在您发表评论后,您似乎正在打开一个空文件。 Please add this at the bottom of that same script and rerun.请将此添加到同一脚本的底部并重新运行。 It will open the file in C:\\Users\\RSS and make sure it does actually contain data?它将打开C:\\Users\\RSS的文件并确保它确实包含数据?

system('C:\Users\RSS\file.txt');

First, of all as you are starting out, it is better to enable all warnings by 'use warnings' and disable all such expression which can lead to uncertain behavior or are difficult to debug by pragma 'use strict'.首先,在您刚开始时,最好通过“使用警告”启用所有警告并禁用所有此类可能导致不确定行为或难以通过编译指示“使用严格”调试的表达式。

As you are dealing with file stream, it is always recommended to the check if you were able to open the stream.当您处理文件流时,始终建议检查您是否能够打开流。 so, try to use croak or die both would terminate the program with a given message.因此,尝试使用 croak 或 die 两者都会以给定的消息终止程序。

Instead of reading inside the while condition, I would recommend checking for end of file.我建议不要在 while 条件中阅读,而是建议检查文件结尾。 So, loop breaks as end is found.因此,当找到结束时循环中断。 Usually, when reading a line you would use it for further processing, so it is good idea to remove end of lines using chomp.通常,在读取一行时,您会将其用于进一步处理,因此最好使用 chomp 删除行尾。

A sample for reading a file in perl can be as follows:在 perl 中读取文件的示例可以如下所示:

#!/user/bin/perl

use strict;
use warnings;

my $newfile = "file.txt";
open (my $fh, $newfile) or die "Could not open file '$newfile' $!";
while (!eof($fh))
{
    my $line=<$fh>;
    chomp($line);
    print $line , "\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM