简体   繁体   English

在Perl中,如果可能,如何将通用菱形(<>)文件句柄传递给子例程?

[英]In Perl, if possible, how do I pass a generic diamond (<>) filehandle to a subroutine?

I have a script that reads input serially on the fly as another job outputs it, and is expected to modify and return it. 我有一个脚本,可以在另一个作业输出时即时读取输入,并希望对其进行修改并返回。 To do more complex modifications, I'd like to be able to capture this input and pass it to a subroutine, which would then return an object to my base script, where I could modify the object as needed, and then write it back out. 要进行更复杂的修改,我希望能够捕获此输入并将其传递给子例程,然后该子例程会将对象返回到我的基本脚本中,在该脚本中,我可以根据需要修改对象,然后将其写回。 Right now, my code looks something like this: 现在,我的代码如下所示:

while (my $line = <>) {
    # Do stuff here to build object
    # When end of record, call writeObject
    # Start new object unless eof
}

sub writeObject {
    # Iterate over object and print to STDOUT
}

I'd like to take the first while loop and convert it into a subroutine that I can then put, along with writeObject , into a small module that I can reuse. 我想进行第一个while循环,并将其转换为一个子例程,然后将其与writeObject一起放入一个可以重用的小模块中。 What I think I need to do is somehow pass <> to this new subroutine, buildObject . 我认为我需要做的是将<>传递给这个新的子例程buildObject I'd then build new scripts that import buildObject and writeObject , and implement a modifyObject routine that will change from script to script. 然后,我将构建导入buildObjectwriteObject新脚本,并实现一个modifyObject例程,该例程会因脚本而modifyObject The other two pieces should be completely reusable, as those parts of the process never change. 其他两个部分应该完全可重用,因为过程的那些部分永远不会改变。 Optimally, the new routine would look something like this: 最佳情况下,新例程应如下所示:

sub buildObjects {
    my ($input) = @_;
    my @objects = ();
    while (<$input>) {
        # Build object, push to @objects when done
    }
    return \@objects;
}

A script using this would look something like this: 使用此脚本的脚本如下所示:

my $obj = buildObjects(<>);

foreach my $object (@$obj) {
    $object = modifyObject($object);
    writeObject($object);
}

<> is short for <ARGV> , so <><ARGV>缩写,所以

buildObjects(\*ARGV);

Tip: ARGV is a magical file handle. 提示: ARGV是一个神奇的文件句柄。 Function that expect an underlying system file handle won't be able to work with it. 期望基础系统文件句柄的函数将无法使用它。 That's not the case for you, though. 不过,对您而言并非如此。

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

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