Perl subroutine references and anonymous subroutines

Source: Internet
Author: User



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; # Subprogram reference, & symbol must be less
&{$ref_sub}(ARGS) # Release the subroutine reference, pass the parameter ARGS
&$ref_sub(ARGS) # Resolve subroutine reference
$ref_sub->(ARGS) # Resolve subroutine reference
$ref_sub->() # Pass null parameter

Sub {...}; # Define anonymous subroutine, no name after sub
$ref_sub = sub {...}; # Anonymous subroutine reference


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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.