confusing filehandle in perl

╄→гoц情女王★ 提交于 2019-12-02 08:58:18

In your second example, you are reading the filehandle in a list context, which I think is the root of your problem.

my $line = <$fh>;

Reads one line from the filehandle.

my @lines = <$fh>;

Reads all the file. Your former example, thanks to the

while (<FH>) {

Is effectively doing the first case.

But in the second example, you are doing the second thing.

AFAIK, you should always use

while (<FH>) {
   # use $_ to access the content
}

or better

while(my $single_line = <FH>) {
   # use $single_line to access the content
}

because while reads line by line where for first loads all in memory and iterates it after.

Even the returns undef on EOF or error, the check for undef is added by the interpreter when not explicitly done.

So with while you can load multi gigabyte log files without any issue and without wasting RAM where you can't with for loops that require arrays to be iterated.

At least this is how I remember it from a Perl book that I read some years ago.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!