Alien has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys !
Long time,no see !
I started reading about ruby , and I became familiar with it,and I really like it's open classes. Is there a way to do that in perl ? Python supports it too .
  • Comment on How could we "implement" Open Classes in Perl ?

Replies are listed 'Best First'.
Re: How could we "implement" Open Classes in Perl ?
by Arunbear (Prior) on Jun 27, 2008 at 07:54 UTC
    Perl classes are based on packages, which are by nature open. So e.g. to add a foo() method to the CGI class you can do
    package main; use strict; use warnings; use CGI; package CGI; sub foo { my $self = shift; return $self->p('foo'); } package main; my $cgi = CGI->new; print $cgi->foo() . "\n";
      Thank you for this great example.

        Since you have direct access to the package via its namespace, you don't even need the package switching. This works too–

        use CGI; my $cgi = CGI->new; print $cgi->foo(), "\n"; sub CGI::foo { my $self = shift; return $self->p('foo'); }
Re: How could we "implement" Open Classes in Perl ?
by BrowserUk (Patriarch) on Jun 27, 2008 at 07:41 UTC

    Unless you go to extraordinary length to close them, most implementations, including the defacto blessed-reference based and inside-out implementations of classes allow you to add or replace methods at runtime.

    For my interest, what is it that you find so desirable about open classes?


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      I think I like them because you don't have to spend all that time on design patterns.