Define a primitive data type: Difference between revisions

(Added Toka)
Line 93:
==[[Perl]]==
[[Category:Perl]]
'''Interpreter:''' [[Perl]] 5.x
 
package One_To_Ten;
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.
use Carp qw(croak);
 
use Tie::Scalar qw();
If you wanted to force a variable to contain a number of 1 .. 10 you could do this:
use base qw(Tie::StdScalar);
 
$var = undef if ($var !~ /^\d+$/ or $var < 1 or $var > 10);
sub STORE {
 
my $self = shift;
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.
my $val = int shift;
croak 'out of bounds' if $val < 1 or $val > 10;
$$self = $val;
};
package main;
tie my $t, 'One_To_Ten';
$t = 3; # ok
$t = 5.2; # ok, silently coerced to int
$t = -2; # dies, too small
$t = 11; # dies, too big
$t = 'xyzzy';
# dies, too small. string is 0 interpreted numerically
 
==[[Toka]]==
Anonymous user