develooper Front page | perl.perl6.language | Postings from April 2006

How do you use a built-in class as a base class?

From:
Dan Kogai
Date:
April 8, 2006 05:07
Subject:
How do you use a built-in class as a base class?
Message ID:
0C2A97E7-70CC-4F6D-98A4-36658ACE0264@dan.co.jp
Folks,

With Perl6, we have singleton methods as

   $me.meta.add_method(me => sub{ ... });

But is there a way to, say, add methods within lexical scope?
Take URI on Perl 5.  URI behaves both as an object

my $uri = URI->new("http://dev.perl.org/perl6/");
print $uri->path; # "/perl6/"

But it also behaves as an ordinary string.

print $uri; # "http://dev.perl.org/perl6/"

In Perl5, this is done by overloading q("").  If you want anything  
like this, you needed overloading.  But in Perl6, I assume you'd go like

class URI is Str {
    method path(){
    # ....
    }
}

So you don't have to resort to overloading.  Now the questions are:

1.  How are you going to initialize?

	my URI $uri .= .new("http://dev.perl.org/perl6/");

   or

	my $uri = URI.new("http://dev.perl.org/perl6/");

   or

  	my URI $uri = "http://dev.perl.org/perl6/";

   ?

2.  How do the method access its internal string.  Via $?SELF ?

Or should I use roles instead of classes in this kind of case?  What  
I want is make something like a "smart builtin classes" within Perl 6  
semantics.  You don't want to go like $uri.meta.add_method('path'  
=> ...), right?


I know how to do that in Perl 5 (possible but difficult).  I know how  
to do that in Javascript (eazy but Str.prototype.yourmeth = function() 
{...} makes ALL STRINGS smart).  What's the recommended way in Perl 6?

Dan the Object Disoriented





nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About