原文: https://beginnersbook.com/2017/02/subroutines-and-functions-in-perl/
Perl 允许您定义自己的函数,称为子程序。它们用于代码可重用性,因此您不必一次又一次地编写相同的代码。例如,如果您想在程序的多个位置从用户那里获取输入,那么您可以在子程序中编写代码并在需要输入的任何位置调用子程序。这样您就不必再次编写相同的代码,这也提高了代码的可读性。
子程序的优点:
1)代码可重用性
2)提高代码可读性
语法:
定义子程序
您需要做的第一件事是创建一个子程序。sub关键字用于定义 Perl 程序中的子程序。您可以选择任何有意义的子程序名称。
sub subroutine_name{statement(s);return;}
调用子程序
通过使用前缀为&的子程序名称来调用子程序。您也可以在调用子程序时传递参数。
&subroutine_name; #calling without parameter&subroutine_name(10);
子程序的简单例子
让我们举一个简单的例子来理解这个:
#!/usr/bin/perlmy $msg;# defining three subroutinessub ask_user {printf "Please enter something: ";}sub get_input {$msg = <STDIN>;return $msg;}sub show_message {printf "You entered: $msg";}#calling subroutines&ask_user;&get_input;&show_message;
输出:
Please enter something: Welcome to beginnersbookYou entered: Welcome to beginnersbook
将参数传递给子程序
在上面的例子中,我们在调用子程序时没有传递任何参数,但是我们可以在调用子程序时传递各种参数。所有参数(通常称为参数)都存储在特殊数组(@_)中。让我们看看下面的例子来理解这个:
#!/usr/bin/perl# defining subroutinesub printparams {printf "@_\n";return;}#calling subroutine&printparams("This", "is", "my", "blog");
输出:
This is my blog
在上面的例子中,我们使用特殊数组(@_)打印了所有参数。但是,如果需要,可以使用$_[n]显示所选参数,其中n是参数的索引,例如$_[0]将引用第一个参数,$_[1]将引用第二个参数。让我们举一个例子:
#!/usr/bin/perl# defining subroutinesub printparams {printf "First Parameter: $_[0]\n";printf "Fourth Parameter: $_[3]\n";return;}#calling subroutine&printparams("This", "is", "my", "blog");
输出:
First Parameter: ThisFourth Parameter: blog
将数组传递给子程序
在上面的例子中,我们在调用子程序时传递了一些字符串参数。我们也可以将数组传递给子程序。这是一个例子:
#!/usr/bin/perl# defining subroutinesub printparams {printf "First Parameter: $_[0]\n";printf "Third Parameter: $_[2]\n";printf "Fourth Parameter: $_[3]\n";printf "Sixth Parameter: $_[5]\n";return;}@array1 = ("This", "is", "text");$num = 100;@array2 = ("Welcome", "here");#calling subroutine&printparams(@array1, @array2, $num);
输出:
First Parameter: ThisThird Parameter: textFourth Parameter: WelcomeSixth Parameter: 100
将哈希传递给子程序
#!/usr/bin/perlsub DisplayMyHash{#copying passed hash to the hashmy %hash = @_;for my $key (keys %hash) {print "Key is: $key and value is: $hash{$key}\n";}}%hash = ('Item1', 'Orange', 'Item2', 'Apple', 'Item3', 'Banana');# Function call with hash parameterDisplayMyHash(%hash);
输出:
Key is: Item1 and value is: OrangeKey is: Item2 and value is: AppleKey is: Item3 and value is: Banana
