
Jasmine
Administrator
/ Moderator
Jan 30, 2000, 10:21 PM
Post #2 of 4
(293 views)
|
|
Re: Including pre-written code
[In reply to]
|
Can't Post
|
|
Rita, It sounds like you want to create a library. Libraries allow you to keep frequently used code in a separate file that you can "include" (using your ssi analogy) as needed. To do this, simply put your subroutines into a separate text file, such as library.pl (make sure there's a 1; as the last line so your library returns a "true" value), and require the library when you need access to the subroutines. Suppose your library.pl had a subroutine named verify_username, which you use to check usernames. You can use the following; <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> require "/path/to/your/library.pl"; &verify_username; </pre><HR></BLOCKQUOTE> For best encapsulation, the actual code in library.pl should all be enclosed within a subroutine, so you don't inadvertantly reassign any variables from your program. You may also wish to further encapsulate your subroutines by passing variables to it, rather than relying on remember what the variable names were. For example, in your program, you can use: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> require "/path/to/your/library.pl"; my $verified = verify_username($username_to_check); if ($verified){ # The user passed the username authentication } else { # The user failed authentication } </pre><HR></BLOCKQUOTE> then in your library, you can use: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> sub verify_username { my ($username) = @_; my $verified = 0; # more code here # Change $verified to 1 if a username passes authentication. return $verified; } </pre><HR></BLOCKQUOTE> In the above, I used the standard pass/fail scheme by giving pass a true value (1), and fail a false value (0). So yes, you can not only set aside regularly used code, but you can also enclose (encapsulate) them into subroutines that will not affect the rest of your program... with the great side effect of not having to remember the variable names used in each subroutine. Hope this helps... good luck!
|