|
perldata - Perl Data Types
Part:
1
2
3
(Continued from previous part...)
Scalar Object Interpretations
When a scalar object is used in an operation, it could be interpreted in three
ways depending on the type of value the operation is expecting:
- A number, if the operation is expecting a numeric value. If the content in the
object is a string, Perl will try to parse it into a number. If parsing failed,
it will be interpreted as 0.
- A string, if the operation is expecting a string value. If the content in the
object is a number, Perl will convert it into a string representation of that number.
- A TRUE or FALSE, if the operation is expecting a boolean value.
Perl will interpret number 0, string '0', and empty string
'' as FALSE, and anything else as TRUE.
To verify the rules listed above, I wrote the following program:
#- ScalarObject.pl
#- Copyright (c) 1995 by Dr. Herong Yang
#
print(0.00, "\n"); # 0
print(00.00, "\n"); # 00
print(1e-1, "\n"); # 0.1
print(1e+50, "\n"); # 1e+050
print(1e+100, "\n"); # 1e+100
print(1e+1000, "\n"); # 1.#INF
print(1e+1000 + 1, "\n"); # 1.#INF
print('1e+1000' + 1, "\n"); # 1.#INF
print(0.1234567890123456789, "\n"); # 0.123456789012346
print(1 / 3, "\n"); # 0.333333333333333
print(1 / '3', "\n"); # 0.333333333333333
print(1 + 3, "\n"); # 4
print(1.3, "\n"); # 1.3
print(1 . 3, "\n"); # 13
print((1 . 3) * 5, "\n"); # 65
print('Hello '. 'world!', "\n"); # Hello world!
print(1 + 'a', "\n"); # 1
print(1 * 'a', "\n"); # 0
print(1 + '', "\n"); # 1
print('FALSE', "\n") if (not 0); # FALSE
print('FALSE', "\n") if (not '0'); # FALSE
print('FALSE', "\n") if (not ''); # FALSE
print('TURE', "\n") if (' '); # TURE
print('TURE', "\n") if (1); # TURE
The outputted values are entered into the program as comments. You
are probably surprised to see some of the outputted values. Me too.
If a scalar variable is used in an operation, its assigned object will be interpreted
and used in the operation. But if a scalar variable is not assigned (undefined), it
will be interpreted as:
- 0, if a numerical value is expected.
- '', if a string value is expected.
- FALSE, if a boolean value is expected.
Here is a program to show you how a undefined scalar variable behaves in an operation:
#- undefined.pl
#- Copyright (c) 1995 by Dr. Herong Yang
#
print '(' . $a . ')', "\n";
print 1 + $a, "\n";
print 1 * $a, "\n";
print 'FALSE', "\n" if (not $a);
(Continued on next part...)
Part:
1
2
3
|