本文介绍了将数据文件读入数组的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据文件,每一行都有一个数字,比如
I have a data file, with each line having one number, like
10
20
30
40
如何读取此文件并将数据存储到数组中?
How do I read this file and store the data into an array?
这样我就可以对这个数组进行一些操作了.
So that I can conduct some operations on this array.
推荐答案
只需将文件读入数组,每个元素一行,很简单:
Just reading the file into an array, one line per element, is trivial:
open my $handle, '<', $path_to_file;
chomp(my @lines = <$handle>);
close $handle;
现在文件的行在数组 @lines
中.
Now the lines of the file are in the array @lines
.
如果您想确保对 open
和 close
进行错误处理,请执行以下操作(在下面的剪辑中,我们以 UTF-8 模式打开文件,也是):
If you want to make sure there is error handling for open
and close
, do something like this (in the snipped below, we open the file in UTF-8 mode, too):
my $handle;
unless (open $handle, "<:encoding(utf8)", $path_to_file) {
print STDERR "Could not open file '$path_to_file': $!\n";
# we return 'undefined', we could also 'die' or 'croak'
return undef
}
chomp(my @lines = <$handle>);
unless (close $handle) {
# what does it mean if close yields an error and you are just reading?
print STDERR "Don't care error while closing '$path_to_file': $!\n";
}
这篇关于将数据文件读入数组的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!