equal
deleted
inserted
replaced
5 |
5 |
6 our $VERSION = '0.01'; |
6 our $VERSION = '0.01'; |
7 |
7 |
8 sub TIESCALAR { |
8 sub TIESCALAR { |
9 my ($class, $type) = @_; |
9 my ($class, $type) = @_; |
10 return bless { value => undef, type => ref $type ? ref $type : $type // '' }; |
10 return bless { |
|
11 value => undef, |
|
12 type => @_ < 2 ? undef |
|
13 : ref($type) ? ref($type) |
|
14 : length($type) ? $type |
|
15 : '' |
|
16 }; |
11 } |
17 } |
12 |
18 |
13 sub FETCH { return $_[0]->{value} } |
19 sub FETCH { return $_[0]->{value} } |
14 |
20 |
15 sub STORE { |
21 sub STORE { |
16 my ($self, $value) = @_; |
22 my ($self, $value) = @_; |
17 my $ref = ref $value // ''; |
23 my $ref = ref $value // ''; |
18 if ($ref ne $self->{type}) { |
24 $self->{type} //= $ref; |
19 croak 'invalid reference type'; |
25 croak 'invalid reference type' if $ref ne $self->{type}; |
20 } |
|
21 return $self->{value} = $value; |
26 return $self->{value} = $value; |
22 } |
27 } |
23 |
28 |
24 __END__ |
29 __END__ |
25 |
30 |
31 |
36 |
32 use Scalar::RefType; |
37 use Scalar::RefType; |
33 |
38 |
34 tie my $h1 => 'Scalar::RefType', {}; |
39 tie my $h1 => 'Scalar::RefType', {}; |
35 tie my $h2 => 'Scalar::RefType', 'HASH'; |
40 tie my $h2 => 'Scalar::RefType', 'HASH'; |
|
41 tie my $h3 => 'Scalar::RefType'; |
36 |
42 |
37 # dies: |
43 $h1 = []; # dies, violates the type |
38 $h1 = []; |
44 $h2 = []; # dies, violates the type |
|
45 |
|
46 $h3 = {}; # sets the type |
|
47 $h3 = []; # dies |
39 |
48 |
40 =head1 DESCRIPTION |
49 =head1 DESCRIPTION |
41 |
50 |
42 This little module allows you to tie the type of a scalar to a specified |
51 This little module allows you to tie the type of a scalar to a specified |
43 reference type. If the refererence type of an assignment violetes the |
52 reference type. If the refererence type of an assignment violates the |
44 tied type, the assignment throws an exception. |
53 tied type, the assignment throws an exception. |
45 |
54 |
46 =head1 AUTHOR |
55 =head1 AUTHOR |
47 |
56 |
48 Heiko Schlittermann <hs@schlittermann.de> |
57 Heiko Schlittermann <hs@schlittermann.de> |