Perl Subroutines
Perl subroutines (subroutine) are user-defined functions.\n\nA Perl subroutine is a separate piece of code that performs a specific task, which can reduce duplicate code and make the program easier to read.\n\nA Perl subroutine is a code block that encapsulates a series of operations or calculations, which can be called repeatedly for reuse in the program.\n\nPerl subroutines help modularize programs, making code easier to understand, maintain, and reuse.\n\nPerl subroutines can appear anywhere in the program, with the following syntax:\n\nsub subroutine{ statements;}\nCalling subroutine syntax:\n\nsubroutine( parameter list );\nFor Perl versions below 5.0, the subroutine is called as follows:\n\n&subroutine( parameter list );\nIn newer versions, although this calling method is also supported, it is not recommended.\n\nNext, let's look at a simple example:\n\n## Example\n\n#!/usr/bin/perl sub Hello{print"Hello, World!n"; }Hello();\n\nExecuting the above program, the output is:\n\nHello, World!\n\n* * *\n\n## Passing Arguments to Subroutines\n\nPerl subroutines can accept multiple parameters like other programming languages, with subroutine parameters denoted by the special array @_.\n\nTherefore, the first parameter of a subroutine is $_, the second parameter is $_, and so on.\n\nRegardless of whether parameters are scalar or array types, when users pass parameters to subroutines, Perl calls them by reference by default.\n\n## Example\n\n#!/usr/bin/perl sub Average{$n = scalar(@_); $sum = 0; foreach$item(@_){$sum += $item; }$average = $sum / $n; print 'The passed arguments are : ',"@_n"; # Print the entire array print "The first argument value is : $_n"; # Print the first argument print "The average of the passed arguments is : $averagen"; # Print the average } # Call function Average(10, 20, 30);\n\nExecuting the above program, the output is:\n\nThe passed arguments are : 10 20 30The first argument value is : 10The average of the passed arguments is : 20\nUsers can change the values of the actual parameters by modifying the values in the @_ array.\n\n### Passing Lists to Subroutines\n\nSince the @_ variable is an array, it can pass lists to subroutines.\n\nHowever, if we need to pass both scalar and array parameters, we need to put the list in the last parameter position, as shown below:\n\n## Example\n\n#!/usr/bin/perl sub PrintList{my@list = @_; print"The list is : @listn"; }$a = 10; @b = (1, 2, 3, 4); PrintList($a, @b);\n\nThe above program combines the scalar and array, and the output is:\n\nThe list is : 10 1
YouTip