You have it backwards. If you want to use closures cleanly and effectively, it's the inner layer of the methods that need to be a closure.
package UsesClosures; sub new { my $attr; return bless({ get_attr => sub { $attr }, set_attr => sub { $attr = $_[1] }, some_method => sub { print "$attr\n"; } }, shift); } sub get_attr { &{ shift->{get_attr } } }; sub set_attr { &{ shift->{set_attr } } }; sub some_method { &{ shift->{some_method} } };
my $o = UsesClosures->new(); $o->set_attr(123); print $o->get_attr(); $o->some_method();

Your Dinner module would be:

package Dinner; sub new { my $hands_clean = 1; return bless({ wash_hands => sub { $hands_clean = 1; }, eat_food => sub { die "Filthy\n if !$hands_clean; print "Om nom nom\n"; }, }, shift); } sub wash_hands { &{ shift->{wash_hands} } }; sub eat_food { &{ shift->{eat_food } } };
my $dirtyeater = Dinner->new(); $dirtyeater->wash_hands(); $dirtyeater->eat_food();

Like inside-out objects, such objects are hard to debug.


In reply to Re: Using closures to achieve data hiding in OO Perl by ikegami
in thread Using closures to achieve data hiding in OO Perl by saurabh.hirani

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.