Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: understanding closures

by shady (Sexton)
on Sep 23, 2005 at 11:27 UTC ( [id://494470]=note: print w/replies, xml ) Need Help??


in reply to understanding closures

Play with it:
#!/usr/bin/perl use warnings; use strict; package Class::GetSet; sub new { my $class = shift; return bless({@_}, $class) } sub __set { $_[0]->{ $_[1] } = $_[2] } sub __get { return $_[0]->{ $_[1] } } use vars qw($AUTOLOAD); sub AUTOLOAD { no strict 'refs'; if ($AUTOLOAD =~ /^.*::(\w+)$/o && exists $_[0]->__has->{$1}->{'rea +d'} ) { my $attr = $1; *{$AUTOLOAD} = sub { my $s = shift; return ($s->__get( +$attr, @_)) }; goto &$AUTOLOAD; } elsif ($AUTOLOAD =~ /^.*::set_(\w+)$/o && exists $_[0]->__ha +s->{$1}->{'write'} ) { my $attr = $1; *{$AUTOLOAD} = sub { my $s = shift; return ($s->__set( +$attr, @_)) }; goto &$AUTOLOAD; } # subs like DESTROY return if $AUTOLOAD =~ /^.*::[A-Z]+$/; die "Unimplemented $AUTOLOAD"; } + + package Dummy; + + use base qw(Class::GetSet); sub __has { return { foo => { read => 1, write => 1 }, bar => { read = +> 1 } } } + + package main; + + my $d = Dummy->new( foo => 1, bar => 2); print "foo = '". $d->foo ."'\n"; $d->set_foo( 'xxx' ); print "foo = '". $d->foo ."'\n"; + + print "bar = '". $d->bar ."'\n"; $d->set_boo( 'xxx' );
Example above is for example of using the closures for dynamic generation of methods.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://494470]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-24 02:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found