As a 75 year old C/C++ programmer, I am wedded to strongly typed languages. This makes it difficult for me to learn perl. In particular, the question of the defined/undefined attribute is very difficult for me to grok. Here's the deal:
My introductory perl book tells me that an undefined numeric variable returns 0 and an undefined array variable returns the empty string. Both values are valid for their respective types. (I am told that I am not supposed to express opinions here, but still I wonder what my program will do with these variable values if I mistakenly thought they were defined.) Anyhow, it is apparent that a perl variable must be implemented with a data structure that contains a defined/undefined indicator. Is this the case?
I have spent a good bit of time cruising the web for an answer, but nobody seems to recognize the issue.
Thanks,
John
I didn't read the perl source and I don't know what else I could have tried.
Yes, Perl variables are backed by internal data structures (called SVs) that include a flag to indicate whether a value is defined. So you're right — Perl keeps track of whether a variable is defined or not. When you use an undefined variable, Perl tries to handle it gracefully: in numeric context it becomes 0
, and in string context it becomes an empty string ""
. But this can easily hide bugs if you're not careful. To catch such mistakes, always use use strict; use warnings;
and check with defined($var)
when needed.