将一个子例程传递给另一子例程 [英] Passing one subroutine to another subroutine

查看:97
本文介绍了将一个子例程传递给另一子例程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 sub _where(\ @ \&),它有2个参数:第一个是数组,第二个应该是另一个函数.这个另一个函数返回一个布尔值,我想在 sub _where(\ @ \&)函数的for循环内调用它.

I have one function sub _where(\@ \&) which takes 2 arguments: the first is an array, and the second should be another function. This other function returns a boolean value, and I want to call it inside my for loop of sub _where(\@ \&) function.

我无法提取要传递给自定义本地名称的函数.我想我确实需要一些本地名称,因为应该可以将不同的布尔函数传递给我的 where 函数.

I am having trouble extracting the function I am passing in into a custom local name. I think I do need some local name for it, because it should be possible to pass different boolean functions to my where function.

其中:

sub _where(\@ \&)
{
    my @stud = @{$_[0]};
    my $student;
    my $function = shift;
    my $bool = 0;
    my $i;

    for $i(0..$#stud)
    {
        my $student = $stud[$i];
        function $student;
    }
}

应传递的Function1:

Function1 that should be passed:

sub name_starts_with($)
{
    my $letter = 'B'; 
    my $student = shift;
    my $first;

    $first = substr($student -> name, 0, 1);

    if($first eq $letter)
    {
        return 1;
    }
}

应该传递给 where 的函数2:

sub points_greater_than($)
{
    my $sum_pts = 5; 
    my $student = shift;
    my $pts;

    $pts = $student -> points;
    if($pts > $sum_pts)
    {
        return 1;
    }
}

希望你们能在这里帮助我.干杯

Hope you guys could help me out here. Cheers

推荐答案

在函数 _where 中的参数处理中存在错误.您正在将数组引用放入 $ function 变量中.你必须要做

You have bug in argument handling in function _where. You are putting array reference into $function variable. You have to do

my @stud = @{shift()};
my $student;
my $function = shift();

my @stud = @{$_[0]};
my $student;
my $function = $_[1];

或者我更喜欢

sub _where(\@ \&)
{
    my ($stud, $function) = @_;

    for my $student (@$stud)
    {
        $function->($student);
    }
}

但不要混合使用这些方法.

but don't mix those methods.

这篇关于将一个子例程传递给另一子例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆