简体   繁体   中英

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. What I think I need to do is somehow pass <> to this new subroutine, buildObject . I'd then build new scripts that import buildObject and writeObject , and implement a modifyObject routine that will change from script to script. 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

buildObjects(\*ARGV);

Tip: ARGV is a magical file handle. Function that expect an underlying system file handle won't be able to work with it. That's not the case for you, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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