企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Perl 中的子程序 > 原文: [https://beginnersbook.com/2017/02/subroutines-and-functions-in-perl/](https://beginnersbook.com/2017/02/subroutines-and-functions-in-perl/) Perl 允许您定义自己的函数,称为**子程序**。它们用于代码可重用性,因此您不必一次又一次地编写相同的代码。例如,如果您想在程序的多个位置从用户那里获取输入,那么您可以在子程序中编写代码并在需要输入的任何位置调用子程序。这样您就不必再次编写相同的代码,这也提高了代码的可读性。 #### 子程序的优点: 1)代码可重用性 2)提高代码可读性 ### 语法: #### 定义子程序 您需要做的第一件事是创建一个子程序。`sub`关键字用于定义 Perl 程序中的子程序。您可以选择任何有意义的子程序名称。 ```perl sub subroutine_name { statement(s); return; } ``` #### 调用子程序 通过使用前缀为`&`的子程序名称来调用子程序。您也可以在调用子程序时传递参数。 ```perl &subroutine_name; #calling without parameter &subroutine_name(10); ``` ### 子程序的简单例子 让我们举一个简单的例子来理解这个: ```perl #!/usr/bin/perl my $msg; # defining three subroutines sub 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; ``` **输出:** ```perl Please enter something: Welcome to beginnersbook You entered: Welcome to beginnersbook ``` ### 将参数传递给子程序 在上面的例子中,我们在调用子程序时没有传递任何参数,但是我们可以在调用子程序时传递各种参数。所有参数(通常称为参数)都存储在特殊数组(`@_`)中。让我们看看下面的例子来理解这个: ```perl #!/usr/bin/perl # defining subroutine sub printparams { printf "@_\n"; return; } #calling subroutine &printparams("This", "is", "my", "blog"); ``` **输出:** ```perl This is my blog ``` 在上面的例子中,我们使用特殊数组(`@_`)打印了所有参数。但是,如果需要,可以使用`$_[n]`显示所选参数,其中`n`是参数的索引,例如`$_[0]`将引用第一个参数,`$_[1]`将引用第二个参数。让我们举一个例子: ```perl #!/usr/bin/perl # defining subroutine sub printparams { printf "First Parameter: $_[0]\n"; printf "Fourth Parameter: $_[3]\n"; return; } #calling subroutine &printparams("This", "is", "my", "blog"); ``` **输出:** ```perl First Parameter: This Fourth Parameter: blog ``` ### 将数组传递给子程序 在上面的例子中,我们在调用子程序时传递了一些字符串参数。我们也可以将数组传递给子程序。这是一个例子: ```perl #!/usr/bin/perl # defining subroutine sub 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); ``` **输出:** ```perl First Parameter: This Third Parameter: text Fourth Parameter: Welcome Sixth Parameter: 100 ``` ### 将哈希传递给子程序 ```perl #!/usr/bin/perl sub DisplayMyHash{ #copying passed hash to the hash my %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 parameter DisplayMyHash(%hash); ``` **输出:** ```perl Key is: Item1 and value is: Orange Key is: Item2 and value is: Apple Key is: Item3 and value is: Banana ```