Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: More than one way......

by ELISHEVA (Prior)
on Jan 31, 2011 at 20:38 UTC ( [id://885353]=note: print w/replies, xml ) Need Help??


in reply to More than one way......

What is correct with global variables really depends on the larger picture of what you are trying to do. Generally you want to try as much as possible to return values rather than set global variables. Perl lets you return lists of variables so you aren't limited to a single return value.

sub myFunc { return (1,2,3); } my @aReturnValues = myFunc();

Second best is passing in an array or reference as a parameter and stuffing generated values into the array or hash parameter. Although this isn't as easy to maintain as a return value, a parameter at least keeps the data and the thing that changes it closely related. As long as you document that the parameter will be modified, you shouldn't have problems from this. But keep in mind, it is easy to forget to read documentation and also not so easy to keep documentation and code in sync. A return value is better.

The only read/write things that should go into global variables are configuration data that your whole program needs. If possible these should be gathered into larger data structures, e.g. a configuration hash or an application object. You should try to keep the number of read/write global variables very small. You should also carefully limit the functions that can change the global data and give the setter functions names that are easy to search for. If you don't, your code will become hard to maintain because you won't be able to keep track of what functions change which variables.

A final closing question: do you have lots of variables ending in $stringN or $messageN where N is some number? If so, perhaps you should consider putting them into an array of arrays (see perldsc). They would be much easier to keep track of and work with that way:

my @strings; my @messages; #process first 65 strings # loop through the numbers 0 thru 64 inclusive for my $i (0..64) { if(substr($strings[$i][$count],0,2) eq "MY") { $messages[$i] = substr($strings[$i][$count],2); } }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://885353]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-24 00:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found