There is automatic conversion between numbers and strings in Perl.
From the Llama book:
You don’t need to worry about the
difference between numbers and
strings; just use the proper
operators, and Perl will make it all
work.And if you’re worried about
efficiency, don’t be. Perl generally
remembers the result of a conversion
so that it’s done only once.
How does this happens? I mean how does Perl remembers it and for how much time?
Doesn’t it affect the efficiency even by a single bit?
Why should the efficiency be slower?
If you do the conversion automatically or manually, it is absolutely the same. But by doing it automatically you just need to type less code.
A scalar variable in perl can hold many different values. The runtime (perl interpreter) does a conversion and saves the number inside the scalar.
You can see such internal things with Devel::Peek
Output:
Here you can see that a Scalar Value (SV) has
"15"the string as (PV), after doing an addition it adds (IV) (Integer Value).A scalar contains a flags to know which value is correct. In the first dump you see the Flag
POKthat saysPVis a correct current value. If you ask for this value,perlcan immediately return this value.After the addition you see “IOK” that says “IV” value is also okay. Actually the variable itself was not changed, but because an addition with a string was made perl needed todo a conversation from string to an int. What you see after the addition is that
POKandIOKare valid. That means the Scalar currently holds a valid string and a valid Integer. As long as the variable doesn’t change, both values are valid, and perl don’t need to do a conversation.But after changing the value to the integer
5you see that “POK” is not set anymore. This operation sets the IV to a new value and invalidates the PV value. As long as you just work with$valueas an integer nothing additional will happen. As soon as you use$valuewithin a string context will will do a conversion to a string and will updatePVand setsPOK. But only has to do that once.