I agree that iterating on @$chain isn't very clean code, because $chain is a global variable. You can of course make a copy of the array @$chain in the __Call_MethodChain__ function. The change is not difficult, the new sub is this:

sub __Call_MethodChain__ { my $r = $_[0]; my @chain = @$chain; for my $pair (@chain) { my($method, $args) = @$pair{"method", "args"}; $r = $r->$method(@$args); } $r; }

Your point with the while loop is especially valid, because my code doesn't propagate context for a method chain call. The simplest version (the one with blessed subs) doesn't have this bug. The simplest way to fix this is a looped shift like this:

sub __Call_MethodChain__ { my $r = $_[0]; my @chain = @$chain; for (;;) { my $pair = shift @chain; my($method, $args) = @$pair{"method", "args"}; 0 == @chain and return $r->$method(@$args); $r = $r->$method(@$args) ; } }

You are right, the straightforward solution can even handle dynamic building of method chains well, and it also doesn't have the bug I've mentioned above. I can still also say that this was just an experiment I made with perl (or even just some filthy trick to get some noderep).


In reply to Re^4: Method chain object with easy syntax by ambrus
in thread Method chain object with easy syntax by ambrus

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.