Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a Perl subroutine that accepts more than one block?

With prototypes, you can create a subroutine that accepts a block of code as its first parameter:

sub example (&) {
   my $code_ref = shift;
   $code_ref->();
}
example { print "Hello\n" };

How can I do the same thing, but with more than one block of code? I want to use blocks of codes, not variables or sub { ... }.

This does not work:

sub example2 (&&) {
   my $code_ref = shift;
   my $code_ref2 = shift;
   $code_ref->();
   $code_ref2->();
}
example2 { print "One\n" } { print "Hello\n" };

It gives this error:

Not enough arguments for main::example2
like image 975
Flimm Avatar asked Nov 20 '14 16:11

Flimm


2 Answers

I hope you realise that this is just code seasoning, and all you are achieving is a tidier syntax at the expense of clarity?

Perl won't allow you to pass more than one bare block to a subroutine, but the second actual parameter could be a call to a subroutine that also takes a single block and simply returns the code reference.

This program demonstrates. Note that I have chosen please and also as names for the subroutines. But you must use something that is both appropriate to your own code's functionality and very unlikely to clash with forthcoming extensions to the core language.

use strict;
use warnings;

sub please(&$) {
  my ($code1, $code2) = @_;
  $code1->();
  $code2->();
}

sub also(&) {
  $_[0];
}

please { print "aaa\n" } also { print "bbb\n" };

output

aaa
bbb
like image 101
Borodin Avatar answered Oct 11 '22 13:10

Borodin


works for me...

sub example2  {
   my $code_ref = shift;
   my $code_ref2 = shift;
   $code_ref->();
   $code_ref2->();
}
example2 ( sub { print "One\n" }, sub { print "Hello\n" });

Just for the purposes of TMTOWTDI here is a method that works in somewhat the way that the OP requested

First, make a source filter

package poop;

use Filter::Util::Call;

sub import {
    my ($type) = @_;
    my ($ref)  = [];
    filter_add( bless $ref );
}

sub filter {
    my ($self) = @_;
    my ($status);
if (( $status = filter_read() ) > 0) { 
        if(!/sub/ && /example2/) {
            s/\{/sub \{/g;
            }
        }

    $status;
}
1;

Second the filter must be used

use poop;

sub example2  {
   my $code_ref = shift;
   my $code_ref2 = shift;
   $code_ref->();
   $code_ref2->();
}
example2 ( { print "One\n" }, { print "Hello\n" });

ps. this is horrific and noone would wish to see this actually in production

like image 38
Vorsprung Avatar answered Oct 11 '22 12:10

Vorsprung