Perl, How do I create a map / grep like routine?

I want to create a subroutine of type grep {} @or map {} @that can handle code and / or logical input. Somehow on the Internet there is not much information about this.

I tried to create a sub below, but it can't even handle the first test. I get an error message Can't locate object method "BoolTest" via package "input" (perhaps you forgot to load "input"?) at C:\path\to\file.pl line 16..

How does it think this is an object? I do not create BoolTest correctly?

# Example senarios
BoolTest { 'input' =~ /test[ ]string/xi };
BoolTest { $_ =~ /test[ ]string/xi } @array;
BoolTest(TRUE);

# Example subroutine
sub BoolTest
{
   if ( ref($_[0]) == 'CODE') {
       my $code = \&{shift @_}; # ensure we have something like CODE
       if ($code->()) { say 'TRUE'; } else { say 'FALSE'; }
   } else {
       if ($_[0]) { say 'TRUE'; } else { say 'FALSE'; }
   }
}
+4
source share
1 answer

To pass a link to the code, you can use the following:

sub BoolTest { ... }

BoolTest sub { 'input' =~ /test[ ]string/xi };
BoolTest sub { $_ =~ /test[ ]string/xi }, @array;
BoolTest(TRUE);

You can have a similar syntax for map BLOCK LISTusing a prototype &@.

sub BoolTest(&@) { ... }

BoolTest { 'input' =~ /test[ ]string/xi };
BoolTest { $_ =~ /test[ ]string/xi } @array;

, return, last .. , .

,

BoolTest(TRUE);

&BoolTest(TRUE);

, . , , .

BoolTest { TRUE };
+5

All Articles