| Previous | Next
SubroutinesSubroutines are declared using one of these forms: sub Prototypes allow you to put constraints on the arguments you provide to your subroutines. You can also create anonymous subroutines at runtime, which will be available for use through a reference: $ Calling SubroutinesThe ampersand (
To call subroutines indirectly (by name or by reference): &$subref( Passing ArgumentsAll arguments to a subroutine are passed as a single, flat list of scalars, and return values are returned the same way. Any arrays or hashes passed in these lists will have their values interpolated into the flattened list. Any arguments passed to a subroutine come in as the array You may use the explicit Passing ReferencesIf you want to pass more than one array or hash into or out of a function and maintain their integrity, you should pass references as arguments. The simplest way to do this is to take your named variables and put a backslash in front of them in the argument list: @returnlist = ref_conversion(\@ This sends references to the three arrays to the subroutine (and saves you the step of creating your own named references to send to the function). The references to the arrays are passed to the subroutine as the three-member Returning references is a simple matter of returning scalars that are references. This way, you can return distinct hashes and arrays. Private and Local VariablesAny variables you use in the function that aren't declared private are global variables. In subroutines, you'll often want to use variables that won't be used anywhere else in your program, and you don't want them taking up memory when the subroutine is not being executed. You also might not want to alter variables in subroutines that might have the same name as global variables. The To scope multiple variables at once, use a list in parentheses. You can also assign a variable in a my @list = (44, 55, 66); my $cd = "orb"; Dynamic variables are visible to other subroutines called from within their scope, are defined with PrototypesPrototypes allow you to design your subroutines to take arguments with constraints on the number of parameters and types of data. To declare a function with prototypes, use the prototype symbols in the declaration line like this:
In this case, the function expects two scalar arguments. The following table gives the various prototype symbols:
A backslash placed before one of these symbols forces the argument to be that exact variable type. For instance, a function that requires a hash variable would be declared like this: sub hashfunc (\%); Unbackslashed A semicolon separates mandatory arguments from optional arguments. For example: sub newsplit (\@$;$); requires two arguments: an array variable and a scalar. The third scalar is optional. Placing a semicolon before A typeglob prototype symbol ( |