Q&A

Q1: How are subroutines different from functions?
A1: They're not; they both refer to the same conceptual things. In this lesson I simply decided to make the distinction so there would not be any confusion about calling built-in functions versus functions you define yourself.

Note that subroutines you define are, in fact, different from the built-in functions; subroutines don't control the number or type of arguments they can receive (at least, not without prototypes), and the rules of whether you can leave off the parentheses for subroutines are different. Future versions of Perl are working toward making programmer-defined subroutines and built-in subroutines closer in behavior.

Q2:Subroutine calls with & look really weird to me. Can I just leave off the &?
A2: Yes, the & is entirely optional. Include it or leave it off—it's your choice.
Q3:I want to pass two arrays into a subroutine and get two arrays out. But the two arrays get squashed into one list on the way in and on the way out. How can I keep the two arrays discrete?
A3: The best way to do this is to use references, but you won't learn about those until Day 19. Another way is to modify global variables inside the subroutine, rather than passing the array data in via an argument list. Yet another way is to compress the arrays into single scalar values (using delimiters), and then expanding them back into arrays inside your subroutine.
Q4:But global variables are evil and bad.
A4: Well, that depends on who you talk to. In Perl, sometimes the best solution to a problem involves a global variable, and if you're careful (declaring globals with my, for example, and making sure you limit the use of those variables), you can get around the disadvantages of global variables.
Q5:So I can't figure it out, are Perl subroutines pass-by-value or pass-by-reference?
A5: They're pass-by-reference as far as the values in the argument list are concerned. Change a value inside the @_ array (for example, modify a string), and that value will change outside as well. However, multiple arrays will get squashed into a single flat list, so you could consider arrays to be pass-by-value. And, if you assign the @_ argument list to one or more local variables, those values will be copied and any changes will not be reflected outside the subroutine.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset