lib/Scalar/RefType.pm
changeset 0 f65c3dd5742a
child 1 82e2b6a853a7
equal deleted inserted replaced
-1:000000000000 0:f65c3dd5742a
       
     1 package Scalar::RefType;
       
     2 use strict;
       
     3 use warnings;
       
     4 use Carp;
       
     5 
       
     6 our $VERSION = '0.01';
       
     7 
       
     8 sub TIESCALAR {
       
     9     my ($class, $type) = @_;
       
    10     return bless { value => undef, type => ref $type ? ref $type : $type // '' };
       
    11 }
       
    12 
       
    13 sub FETCH { return $_[0]->{value} }
       
    14 
       
    15 sub STORE {
       
    16     my ($self, $value) = @_;
       
    17     my $ref = ref $value // '';
       
    18     if ($ref ne $self->{type}) {
       
    19 	croak 'invalid reference type';
       
    20     }
       
    21     return $self->{value} = $value;
       
    22 }
       
    23 
       
    24 __END__
       
    25 
       
    26 =head1 NAME
       
    27 
       
    28  Scalar::RefType - simple scalar type checker
       
    29 
       
    30 =head1 SYNOPSIS
       
    31 
       
    32  use Scalar::RefType;
       
    33 
       
    34  tie my $h1 => 'Scalar::RefType', {};
       
    35  tie my $h2 => 'Scalar::RefType', 'HASH';
       
    36 
       
    37  # dies:
       
    38  $h1 = [];
       
    39 
       
    40 =head1 DESCRIPTION
       
    41 
       
    42 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 
       
    44 tied type, the assignment throws an exception.
       
    45 
       
    46 =head1 AUTHOR
       
    47 
       
    48 Heiko Schlittermann <hs@schlittermann.de>
       
    49 
       
    50 =cut