How to create a Perl subroutine that accepts a block of code

后端 未结 4 820
猫巷女王i
猫巷女王i 2021-02-01 06:12

I have a set of subroutines that look like this:

sub foo_1($) {
  my $name = shift;
  my $f; 

  run_something();
  open($f, $name) or die (\"Couldn\'t open $nam         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-01 06:48

    sub bar {
       my ($coderef) = @_;
       ⁝
       $coderef->($f, @arguments);
       ⁝
    }
    
    bar(sub { my ($f) = @_; while … }, @other_arguments);
    

    or perhaps a bit less tangled with a named coderef:

    my $while_sub = sub {
        my ($f) = @_;
        while …
        ⁝
    };
    bar($while_sub, @other_arguments);
    

    Edit: The Higher-Order Perl book is full of this sort of programming.

提交回复
热议问题