Perl子例程可以返回数据但可以继续处理吗?

编程入门 行业动态 更新时间:2024-10-18 09:18:04
本文介绍了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子例程可以返回数据但可以继续处理吗?

本文发布于:2023-11-28 15:20:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:例程   数据   Perl

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!