Perl Learning Notes (iv)--subroutines

Source: Internet
Author: User

To define a sub-program :

To define your own subroutine, you can use the keyword sub, the subroutine name (not including the number), and the block of code enclosed in curly braces, for example:

1 Sub marine{2      $n + =1;  # global variable $n 3      Print $n \n "; 4 }

Subroutines do not need to be declared beforehand

The definition of a subroutine is global and there is no private subroutine

If you define two sub-programs with the same name, the following subroutine overwrites the

Calling a sub-program

1 &marine;

return value

The result of the last operation in the subroutine is automatically treated as the return value of the subroutine.

Parameters

To pass a list of arguments to a subroutine, simply add a list expression that is enclosed by parentheses after the subroutine call, for example:

1 $n = &max (N);

Private variables in sub-programs

By default, all of the variables in Perl are global variables, and you can use the My operator to create private variables, which we call lexical variables

1  Submax{2      my($m,$n);#The new private variable in the statement block3($m,$n) =@_;#Assigning a parameter to a variable4      If($m>$n){$m}Else{$n}    5}

the improved &max Sub-Program

1 $maxinum=$max(3,5,Ten,4,6);2 Submax{3     my($max _so_far) =Shift @_;#the first value in the array, temporarily treating it as a maximum value4     foreach(@_){#traversing other elements in the array @_5      if($_>$max _so_far){#is the current element larger than $max_so_far?6          $max _so_far=$_;7      }8     }9     $max _so_far;Ten}

Use Strict Compiling Instructions

More rigorous code and compilation style

return operator

Immediately stop executing the subroutine and return a value

Perl Learning Notes (iv)--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.