Preliminary study on PERL subroutine parameters

xiaoxiao2021-03-06  75

In Perl, the subroutine uses a list of variable length parameters, so the number of parameters is no longer restricted, reflecting the advantages of dynamic language. Since the passed is a reference, it can be changed in the SUB.

SAMLE01.PL

#! / usr / bin / perl

Sub sub_routine {

$ _ [0] = "Hello"; $ _ [1] = 999;

Print "SUB_PAR1: $ _ [0] / N";

Print "SUB_PAR2: $ _ [1] / N";

}

MY $ PAR1 = "Abcde";

MY $ PAR2 = 2;

Print "Main_par1: $ PAR1 / N";

Print "Main_PAR2: $ PAR2 / N";

& Sub_Routine ($ PAR1, $ PAR2);

Print "Main_par1: $ PAR1 / N";

Print "Main_PAR2: $ PAR2 / N";

operation result:

Main_par1: abcde

Main_par2: 2

SUB_PAR1: Hello

Sub_par2: 999

Main_par1: Hello

Main_par2: 999

If you do not want to change the value of the parameters in the subroutine, you can use a method of local variables.

Sample02.pl

#! / usr / bin / perl

Sub sub_routine {

MY $ PAR1 = $ _ [0];

MY $ PAR2 = $ _ [1];

$ PAR1. = "fghijklmn";

$ PAR2 = 10000;

Print "SUB_PAR1: $ PAR1 / N";

Print "SUB_PAR2: $ PAR2 / N";

}

MY $ PAR1 = "Abcde";

MY $ PAR2 = 2;

Print "Main_par1: $ PAR1 / N";

Print "Main_PAR2: $ PAR2 / N";

& Sub_Routine ($ PAR1, $ PAR2);

Print "Main_par1: $ PAR1 / N";

Print "Main_PAR2: $ PAR2 / N";

operation result:

Main_par1: abcde

Main_par2: 2

Sub_par1: Abcdefghijklmn

SUB_PAR2: 10002

Main_par1: abcde

Main_par2: 2

转载请注明原文地址:https://www.9cbs.com/read-93053.html

New Post(0)