... can we add new methods to a exist object in a package?

Update: WRT choroba's reply here, this reply addresses Perlish OO in general.

Yes, it's a new topic, but...

c:\@Work\Perl\monks>perl use 5.014; # needs package NAME BLOCK syntax use strict; use warnings; package Foo { use strict; use warnings; sub new { my $class = shift; return bless { 'hi' => 'lo' } => $class; } sub method { my $self = shift; my ($k) = @_; return exists $self->{$k} ? $self->{$k} : 'unknown'; } } my $of = Foo->new; printf "A: '%s' \n", $of->method('hi'); printf "B: '%s' \n", $of->method('xx'); printf "C: '%s' \n", $of->oh_by_the_way('hi'); printf "D: '%s' \n", $of->oh_by_the_way('xx'); printf "E: '%s' \n", $of->method('hi'); sub Foo::oh_by_the_way { my $self = shift; my ($k) = @_; $_ .= $_ for values %$self; return exists $self->{$k} ? $self->{$k} : $self->method($k); } __END__ A: 'lo' B: 'unknown' C: 'lolo' D: 'unknown' E: 'lolololo'
The basic idea is that a subroutine in any package/namespace can be defined from within any other package/namespace if the newly-defined symbol is fully qualified.


Give a man a fish:  <%-{-{-{-<


In reply to Re^5: how to export a method by AnomalousMonk
in thread how to export a method by toothedsword

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.