Per*_*ker 6 parallel-processing perl return-value subroutine
有没有办法让子程序在处理时发回数据?例如(此示例仅用于说明) - 子例程读取文件.当它正在读取文件时,如果满足某些条件,则"返回"该行并继续处理.我知道有些人会回答 - 你为什么要那样做?你为什么不......?,但我真的想知道这是否可能.
实现此类功能的常用方法是使用回调函数:
{
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;
Run Code Online (Sandbox Code Playgroud)
或者甚至没有命名回调:
process_file 'myfile.txt', sub {print STDERR @_};
Run Code Online (Sandbox Code Playgroud)