Define a primitive data type: Difference between revisions

Content added Content deleted
(New page: {{task}} Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or ...)
 
No edit summary
Line 10: Line 10:
B : My_Type := A;
B : My_Type := A;
The compiler will omit bounds checking for the assignment of A to B above because both values are of My_Type. A cannot hold a value outside the range of 1..10, therefore the assignment cannot produce an out of bounds result.
The compiler will omit bounds checking for the assignment of A to B above because both values are of My_Type. A cannot hold a value outside the range of 1..10, therefore the assignment cannot produce an out of bounds result.

==[[Perl]]==
[[Category:Perl]]
'''Interpreter:''' [[Perl]] 5.x

Perl internally handles variables. As far as simple variables go, there are strings and there are numerical variables. Perl also automatically converts from one to the other based on your use.

If you wanted to force a variable to contain a number of 1 .. 10 you could do this:

$var = undef if ($var !~ /^\d+$/ or $var < 1 or $var > 10);

Which is a check I expect you would have to do in any other language anyway to prevent the program from having problems if the user provided data out side the acceptable range.