Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 828
Perl QuestionAsker Avatar asked Apr 29 '10 20:04

Perl QuestionAsker


People also ask

How do I return a value from a subroutine in Perl?

return() function in Perl returns Value at the end of a subroutine, block, or do function. Returned value might be scalar, array, or a hash according to the selected context.

How do I return multiple values from a Perl subroutine?

Calling a Perl subroutine that returns multiple values When you call a Perl subroutine that returns multiple values, you just need to use a syntax like this: ($a, $b) = foo; This assigns the returned values to my Perl variables $a and $b.

What is subroutine in Perl explain with suitable example?

A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again.

How do you perform a forward declaration of a subroutine performed in Perl?

To declare a subroutine, use one of these forms: sub NAME ; # A "forward" declaration. sub NAME ( PROTO ); # Ditto, but with prototype.


2 Answers

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 @_};
like image 150
Eric Strom Avatar answered Oct 01 '22 22:10

Eric Strom


Some languages offer this sort of feature using "generators" or "coroutines", but Perl does not. The generator page linked above has examples in Python, C#, and Ruby (among others).

like image 37
Greg Hewgill Avatar answered Oct 01 '22 22:10

Greg Hewgill