Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re^6: detecting an undefined variable

by AnomalousMonk (Archbishop)
on Sep 21, 2019 at 20:25 UTC ( [id://11106511]=note: print w/replies, xml ) Need Help??


in reply to Re^5: detecting an undefined variable
in thread detecting an undefined variable

From this:

If I had then used a variable called $scale, it would be handy to know whether that variable existed in the calling code or whether I now had to declare and define it anew.
If I correctly understand what you're getting at, that's what strict is for, and it'll tell you that real fast! If a package variable is not in scope at a point in your code or does not exist at all, you must then declare or define it, respectively, e.g. with our. If a lexical does not exist, you must define it (and usually initialize it) with my in that scope.

Typically, the function in question would be written long before the calling code and would, in fact, end up being called by many different bits of code. Some might define $scale one way, some another, and some not at all.

This sounds like you are creating a hodge-podge of global variables. If so, you are building a nightmare for yourself. Best practice generally dictates that variables, insofar as possible, should be lexical and have as limited a scope as possible | is reasonable. (Constants are another story; you can go crazy with constants!) Ideally, a function should access variables only as arguments passed to the function and never as external variables; thereby, it doesn't matter where or when the function was defined or from where it's called. Of course, it's not always possible to follow best practices and write ideal code, but my (bitter!) experience is that one should immediately question one's motives whenever one is tempted to stray from the Straight Path and indulge unclean practices.

Update: ... as limited a scope as possible. Having read GrandFather's reply, I think "reasonable" is the better word here.


Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-04-19 16:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found