Caleb Cushing's Blog

Perl Core Syntax Wishlist: Class support

I would like to see the class keyword become part of Perl, but unlike some I don’t want it simply because it’s nicer syntax. I’d like it to behave differently from package. I’d basically like to see this

class MyClass {
method foo { return $self->{foo} }
method info { return load_class(‘Class::Info’)->new }

to be the equivalent of

use strict;
use warnings;
use utf8; # so our class can be named with utf8
package MyClass {
use namespace::autoclean;
use Scalar::Util qw( blessed );
# use Class::Load qw( loadclass );
# or similar for a feature that I’m hoping will be in Class::Load in the future
# for now I’ll show with require

sub new { # or something better, point is that there’s a default simple constructor
my $class = shift;
my $self = ref $
[0] eq ‘HASH’ ? $[0] : { @ };

bless $self, $class;
return $self;
sub foo { my $self = shift; return $self->{foo} }

sub info { #doesn’t actually do what I’m really suggesting
my $self = shift;
require Class::Info;
return Class::Info->new;


I’m sure smarter people than I could think of a few more things that might be nice to have by default in all classes. I would like to note that method signatures is not that big of a deal to me, unless of course you want to give me named variables in the signature besides just auto shifting off self, e.g. method foo ( $bar ) { return $self->{foo} if $bar }


comments powered by Disqus