Perl subroutine references and anonymous subroutines

Source: Internet
Author: User

Tags: array description \ n Program call ... one LLB no

Subroutines also have references, as well as anonymous subroutines. Suppose you already have an array, hash reference knowledge, so here is a brief introduction.

$ref_sub = \&mysub;      # 子程序引用,&符号必须不能少&{$ref_sub}(ARGS)        # 解除子程序引用,传递参数ARGS&$ref_sub(ARGS)          # 解除子程序引用$ref_sub->(ARGS)         # 解除子程序引用$ref_sub->()             # 传递空参数sub {...};               # 定义匿名子程序,sub后面没有名称$ref_sub = sub {...};    # 匿名子程序的引用

With the subroutine reference, you can invoke the subroutine on demand.

For example:

sub java_learn {    print "Learning Java now\n";}sub perl_learn {    print "Learning Perl now\n";}sub python_learn {    print "Learing Python now\n";}%sub_hash=(    "javaer"   => \&java_learn,    "perler"   => \&perl_learn,    "pythoner" => \&python_learn,);while(my ($who,$sub)=each %sub_hash){    print "$who is learning\n";    $sub->();}

Change to Anonymous subroutine:

$javaer = sub {    print "Learning Java now\n";};$perler = sub {    print "Learning Perl now\n";};$pythoner = sub {    print "Learing Python now\n";};foreach (qw(javaer perler pythoner)){    print "$_ is learning\n";    $$_->();}

Even, use the anonymous subroutine as part of the data structure:

%sub_hash = (    "javaer" => sub {        print "Learning Java now\n";    },    "perler" => sub {        print "Learning Perl now\n";    },    "pythoner" => sub {        print "Learning Python now\n";    },);while( my($who,$sub)=each %sub_hash ){    print "$who is learning\n";    $sub->();}

The maximum effect of subroutine references and anonymous subroutines may be for callback functions (callback), closures (closure). This topic is a bit big, see the next article.

Perl subroutine references and anonymous subroutines

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: