Hey, I am learning Perl but I just cannot quite understand how the subroutines (Functions) work in Perl Here are some examples of a script and if someone could explain it line by line and how it is doing what it is then I would really appreciate it use strict; sub HowdyEveryone { my($name1, $name2) = @_; return "Hello $name1 and $name2.\n" . "Where do you want to go with Perl today?\n"; } print &HowdyEveryone("bart", "lisa"); Code (markup): Source: http://www.faqs.org/docs/pperl/pickingUpPerl_8.html Thanks in advance!
Ok, I will try to explain: use strict; PHP: Tells PERL to check if every variable is defined before it is used. If you just start using a variable without declaring it with "my", the script will crash. print &HowdyEveryone("bart", "lisa"); PHP: This is first real line that is executed. It tells PERL to call the function HowdyEveryone with 2 parameters "bart" and "lisa" and print the result to the screen. sub HowdyEveryone { my($name1, $name2) = @_; return "Hello $name1 and $name2.\n" . "Where do you want to go with Perl today?\n"; } PHP: This is the subroutine. "@_" is an array with the 2 variables "bart" and "lisa", ($name1, $name2) is also an array because of the brackets (). "bart" becomes $name1, "lisa" $name2. Other ways to do the same: my $name1 = shift; my $name2 = shift; PHP: The effect is the same. "shift" shifts the elements in the array @_ or: my $name1 = $_[0]; my $name2 = $_[1]; PHP: The next 2 lines return a text with the 2 variables. "return" always ends the function. The text is printed to the screen because of the "print" statement outside the function.
Ah ok, that makes much more sense to me now, I think am almost there, just one other question though. What is the using "my" about in the subroutine? I don't understand what it is and what it does there. Thank you for your explanation, much appreciated!
The "my" keyword changes the scope of a variable. Using it inside the function makes the variable local to the subroutine.