Search code examples
perlparallel-processingreturn-valuesubroutine

Can a Perl subroutine return data but keep processing?


Is there any way to have a subroutine send data back while still processing? For instance (this example used simply to illustrate) - a subroutine reads a file. While it is reading through the file, if some condition is met, then "return" that line and keep processing. I know there are those that will answer - why would you want to do that? and why don't you just ...?, but I really would like to know if this is possible.


Solution

  • A common way to implement this type of functionality is with a callback function:

    {
        open my $log, '>', 'logfile' or die $!;
        sub log_line {print $log @_}
    }
    
    sub process_file {
        my ($filename, $callback) = @_;
        open my $file, '<', $filename or die $!;
        local $_;
        while (<$file>) {
            if (/some condition/) {
                 $callback->($_)
            }
            # whatever other processing you need ....
        }
    }
    
    process_file 'myfile.txt', \&log_line;
    

    or without even naming the callback:

    process_file 'myfile.txt', sub {print STDERR @_};