[% setvar title Stronger typing through tie. %]

This file is part of the Perl 6 Archive

Note: these documents may be out of date. Do not use as reference!

To see what is currently happening visit http://www.perl6.org/

TITLE

Stronger typing through tie.

VERSION

  Maintainer: Michael Fowler <michael@shoebox.net>
  Date: 2 Aug 2000
  Mailing List: perl6-language@perl.org
  Number: 15
  Version: 1
  Status: Developing

ABSTRACT

Strong typing of variables can be implemented through the already-existent tie mechanism.

DESCRIPTION

Several people have requested strong typing as a feature, but have been shot down with reasons such as "it's un-Perl-like", with an added "it'll slow everything down for those who don't want it". However, I think it can be done in a fairly simple way through the use of the tie mechanism, which makes the feature optional to those who want an even stricter environment.

Through a pragma or core module one gets various subroutines that produce tied variables that verify they're only set to allowable values. Unfortunately, accessing and manipulating tied variables is incredibly slow, so improving their speed is a large part of making this proposal feasible.

IMPLEMENTATION

I envision syntax like this:

    use typing;  # place your fingers on the home row..

    integer $foo, $bar, $blah;
    string($baz, $qux) = ("bazarific", "quxaroni");

    # and even..

    my integer $quux = 4;

integer and string are subroutines automatically exported by typing.pm; they simply tie their arguments to an appropriate class.

The last is a little questionable; it would require some magic on perl's part to invoke some method or constructor for initializing $quux. A suggested alternative is something like my $quux : integer, but it requires some manipulation on perl's part as well.

There is a drawback: exceptions raised ("That's not an integer!" *croak*) are made at run-time, rather than compile-time (as would be more useful). As a result you have to test all code paths if you are to use this as any sort of internal sanity checking; I assume most everyone does this, but it would be useful for it to be a compile-time check, so that perl -c would catch all of your errors. This could possibly be accomplished by allowing arguments to the pragma or variable initialization.

    use typing qw(very-strict);
    my integer $foo : very-strict = 4;

Which would enforce that you can only assign integer constants to $foo (which are seen at compile-time), or other similarly declared integers (or possibly promoted floats, chars, etc. if you wanted to get C-like). This, then, could allow you to do checking at compile-time.

Which then raises a few more problems (whew): how do you coax user input (which is an SV) into a value $foo can accept with very-strict on?; what happens when an external function (say, from a module) is being very-strict, but is passed arguments from code that doesn't do type checking?

REFERENCES

perldoc perltie