在 Perl 中打开和读取文件的最佳方式是什么?
请注意 - 我不是在寻找打开/读取文件的正确"方式,或者我每次都应该打开/读取文件的方式.我只是有兴趣找出大多数人使用的方式,并且可能同时学习一些新方法:)*
Please note - I am not looking for the "right" way to open/read a file, or the way I should open/read a file every single time. I am just interested to find out what way most people use, and maybe learn a few new methods at the same time :)*
我的 Perl 程序中一个非常常见的代码块是打开一个文件并读取或写入它.我见过很多这样做的方法,而且我执行这项任务的方式多年来已经改变了几次.我只是想知道最好(如果有最好的方法)方法是什么?
A very common block of code in my Perl programs is opening a file and reading or writing to it. I have seen so many ways of doing this, and my style on performing this task has changed over the years a few times. I'm just wondering what the best (if there is a best way) method is to do this?
我曾经像这样打开一个文件:
I used to open a file like this:
my $input_file = "/path/to/my/file";
open INPUT_FILE, "<$input_file" || die "Can't open $input_file: $!
";
但我认为这在错误捕获方面存在问题.
But I think that has problems with error trapping.
添加括号似乎可以修复错误陷阱:
Adding a parenthesis seems to fix the error trapping:
open (INPUT_FILE, "<$input_file") || die "Can't open $input_file: $!
";
我知道您也可以将文件句柄分配给变量,因此我可以使用 $input_filehandle,而不是像上面那样使用INPUT_FILE"——这样更好吗?
I know you can also assign a filehandle to a variable, so instead of using "INPUT_FILE" like I did above, I could have used $input_filehandle - is that way better?
对于读取一个文件,如果它很小,像这样 globbing 有什么问题吗?
For reading a file, if it is small, is there anything wrong with globbing, like this?
my @array = <INPUT_FILE>;
或
my $file_contents = join( "
", <INPUT_FILE> );
或者你应该一直循环,像这样:
or should you always loop through, like this:
my @array;
while (<INPUT_FILE>) {
push(@array, $_);
}
我知道在 perl 中有很多方法可以完成任务,我只是想知道是否有首选/标准的打开和读取文件的方法?
I know there are so many ways to accomplish things in perl, I'm just wondering if there are preferred/standard methods of opening and reading in a file?
没有通用的标准,但有理由偏爱其中一个.我的首选形式是这样的:
There are no universal standards, but there are reasons to prefer one or another. My preferred form is this:
open( my $input_fh, "<", $input_file ) || die "Can't open $input_file: $!";
原因是:
- 您立即报告错误.(如果这是您想要的,请将死亡"替换为警告".)
- 您的文件句柄现在是引用计数的,因此一旦您不使用它,它将自动关闭.如果您使用全局名称 INPUT_FILEHANDLE,那么您必须手动关闭该文件,否则它会一直保持打开状态,直到程序退出.
- 读取模式指示符<"与 $input_file 分开,提高可读性.
如果文件很小并且您知道需要所有行,则以下内容非常有用:
The following is great if the file is small and you know you want all lines:
my @lines = <$input_fh>;
如果您需要将所有行作为单个字符串处理,您甚至可以这样做:
You can even do this, if you need to process all lines as a single string:
my $text = join('', <$input_fh>);
对于长文件,您需要使用 while 遍历行,或使用 read.
For long files you will want to iterate over lines with while, or use read.