简体   繁体   English

如何将打开的文件句柄作为函数的参数传递?

[英]How do I pass an opened filehandle as the parameter of a function?

I have a main script that calls a function from another module. 我有一个从其他模块调用函数的主脚本。 I open a file in the main script, and I want to use the filehandle attached to this file as a parameter in the function called (I don't want to open the file in the function because I will be calling the same function on the same file several times, so opening it every time wouldn't make sense). 我在主脚本中打开了一个文件,并且我想使用附加到此文件的文件句柄作为函数中的参数(我不想在函数中打开文件,因为我将在相同的文件多次,因此每次打开都没有意义)。

In my main script: 在我的主脚本中:

open(my $IN_FILE, "<input.txt") or die "Can't open: $!\n";
open(my $OUT_FILE, ">output.txt") or die "Can't open: $!\n";

AnotherModule->ProcessDBU($IN_FILE, $OUT_FILE); 

In AnotherModule : AnotherModule

sub ProcessDBU{
    my $IN_FILE = $_[0];
    my $OUT_FILE = $_[1];

    local $/ = ' ';

    while(<$IN_FILE>){
        SomeProcess();
    }
} 

However, when I try to run the script, this error occurs: 但是,当我尝试运行脚本时,会发生此错误:

readline() on unopened filehandle at AnotherModule.pm line 7.

What's preventing me from using the filehandle? 是什么让我无法使用文件句柄? Why is it unopened? 为什么未打开? What can I do to fix this problem? 我该怎么做才能解决此问题?

You are calling a function as a method. 您正在将函数作为方法进行调用。

AnotherModule->ProcessDBU($IN_FILE, $OUT_FILE); 

should be 应该

AnotherModule::ProcessDBU($IN_FILE, $OUT_FILE); 

Three differences: 三点不同:

  • Method calls search the inheritance hierarchy, 方法调用搜索继承层次结构,
  • method calls ignore prototypes, and 方法调用忽略原型,并且
  • method calls pass the invocant (what's left of -> ) as the first argument. 方法调用将调用方( ->的左边)作为第一个参数。

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

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