"be consistent" | |
PerlMonks |
Re: Tk Entry widget confusionby hv (Prior) |
on Jul 12, 2024 at 11:19 UTC ( [id://11160563]=note: print w/replies, xml ) | Need Help?? |
This is probably the primary magic of Perl: values are silently converted to the type required for the operator acting on them as far as possible. Behind the curtain, it caches those conversions and remembers whether they are exact or lossy. This also allows for fun tricks, such as "dualvars" that have a different cached value in the string slot and the integer slot - that's used, for example, to allow $! to reveal both the error message and the error number:
You can see what's going on in gory detail with a module such as Devel::Peek:
$val is a scalar value ("SV") as opposed to an array value ("AV"), hash value ("HV"), or something more exotic. The SV has slots for a string ("pointer value" = "PV"), an integer ("IV") and a (floating-point) numeric value ("NV"). In the example above, we start off with a plain string (PV = ""). Then we replace it with an integer 0 (IV = 0, PV is cleared out); then we use that in a string context so it generates and caches the stringified version (PV = "0"). The hex values in there are memory addresses. You don't normally care about them, but it can be useful to see whether two memory addresses are the same or not. I've grepped out most of the gore here; that includes the reference count (which Perl uses to know when a value should be freed); the length of the string value (CUR) and how much memory is allocated for it (LEN, confusingly); flags that say which of the value slots are valid (IOK, POK, NOK) and partially valid (pIOK, pPOK, pNOK); and a flag (IsCOW) and associated reference count if the string is sharable, as a memory saving. Almost all of the time you don't need to know any of this, but having at least some clue what's going on behind the curtain can be very helpful to make Perl seem more predictable.
In Section
Seekers of Perl Wisdom
|
|