Q&A

Q1:How is declaring global variables with my any advantage over using regular global variables if I'm writing self-contained scripts to do very simple things?
A1: If the only scripts you write are smaller, self-contained scripts, then you don't really need to use use strict or make sure your variables are declared using my. You'd use my globals if there was a chance for your code being incorporated into someone else's code, even accidentally. Because quite a lot of code has a chance of being used in ways contrary to how you intended it to be used, the use of my globals and use strict is considered a defensive move and good-programming practice. But it is not required.
Q2:Most languages use either lexical or dynamic scope, but not both. Why does Perl confuse things and provide multiple kinds of local scopes?
A2: It's mostly historical. Earlier versions of Perl provided a dynamic scope for variables with the local operator. The my operator was added later to provide a more distinct lexical local scope; local stays around for backward compatibility with earlier scripts.

If the difference seems hopelessly confusing, just use my variables and assume they are private to any given subroutine, and you'll be fine.

Q3:I've got an older script that someone wrote that starts out with a lot of 'require thislibrary.pl' lines. Should I change those to use use instead?
A3: Actually, no. The require operator was the old way of incorporating library code into Perl scripts, and it's likely that the library you're importing (thislibrary.pl in your example) isn't written as a module, and won't work well with use. Unless you're intending to rewrite the entire script—and potentially rewrite all the libraries as well—you can go ahead and continue to use require.
Q4:I've got a module called Mail which is supposed to give me access to subroutines for sending and receiving mail: send_mail() and rec_mail(). I've imported the module with use, but I keep getting undefined errors for those two subroutines.
A4: Sounds like the module doesn't explicitly import those subroutine names. You have two choices: You can import them yourself, or you can call those subroutines using the full package names:
use Mail;  # import defaults, if any
use Mail qw(send_mail rec_mail);  # import subroutines
send_mail();
# OR
&Mail::send_mail();  # call subroutine with full package name

..................Content has been hidden....................

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