在Perl中使用文件句柄

Laz*_*zer 0 scripting perl file-io

comparefiles在Perl中编写一个子程序,它从一个文件(f1)中读取一行文本,然后f2以正常O(n^2)方式在另一个文件中搜索它.

sub comparefiles {
    my($f1, $f2) = @_;
    while(<f1>) {
        # reset f2 to the beginning of the file
        while(<f2>) {
        }
    }
}

sub someother {
    open (one, "<one.out");
    open (two, "<two.out");
    &comparefiles(&one, &two);
}
Run Code Online (Sandbox Code Playgroud)

我有两个问题

  • 如何将文件句柄传递给子例程?在上面的代码中,我将它们用作标量.这是正确的方法吗?
  • 如何将文件指针重置f2到上面注释中标记位置的文件开头?

Tot*_*oto 8

首先,每次你的脚本开始:

use strict;
use warnings;
Run Code Online (Sandbox Code Playgroud)

使用词法文件句柄,打开三个args并测试结果:

open my $fh1 , '<' , $filename1 or die "can't open '$filename1' for reading : $!";
Run Code Online (Sandbox Code Playgroud)

然后你可以将文件句柄传递给子:

comparefiles($fh1, $fh2);
Run Code Online (Sandbox Code Playgroud)

要回放文件,请使用搜索功能(perldoc -f seek)

seek $fh, 0, 0;
Run Code Online (Sandbox Code Playgroud)