本文介绍了Perl子例程可以返回数据但可以继续处理吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么办法让子例程在仍在处理的同时将数据发送回去?例如(此示例仅用于说明)-子例程读取文件.在读取文件时,如果满足某些条件,则返回"该行并继续进行处理.我知道有些人会回答-您为什么要这样做?以及为什么不只是...?,但我真的很想知道这是否可行.
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.
推荐答案实现此类功能的常用方法是使用回调函数:
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;,甚至没有命名回调:
process_file 'myfile.txt', sub {print STDERR @_};更多推荐
Perl子例程可以返回数据但可以继续处理吗?
发布评论