[Cascavel-pm] evitando estruturas "switch-case" em métodos de uma classe

Nilson Santos Figueiredo Junior acid06 em gmail.com
Sexta Março 30 19:47:07 PDT 2007


On 3/30/07, Nilson Santos Figueiredo Junior <acid06 em gmail.com> wrote:
> On 3/30/07, Flavio S. Glock <fglock em gmail.com> wrote:
> > Ah, a propósito desta observação:
> >
> > use strict;
> > use warnings;
> >
> > package Obj;
> >
> >  sub to_xml {
> >   print 'process xml...';
> >  }
> >
> >  sub to_html {
> >   print 'process html...';
> >  }
> >
> >  sub dispatch {
> >      no strict "refs";
> >      $_[1]->(@_[0,2..$#_]);
> >  };
> >
> > package main;
> >
> > my $obj = bless {}, 'Obj';
> > foreach (qw(to_xml to_html)) {
> >   $obj->dispatch($_);
> >  }
>
> E se eu for um mal usuário desta classe?
>
>   $obj->dispatch( sub {
>       no strict 'refs';
>       map  { undef *{ref($_[0])."::$_"} }
>       grep {$_ =~ /^to_/ and defined *{ref($_[0])."::$_"}{CODE} }
>       keys %{ref($_[0]).'::'};
>   } );

Ou ainda, de forma menos danosa e mais divertida:

$obj->dispatch( sub {
    no strict 'refs';
    map  {
        *{ref($_[0])."::$_"} = sub { print "just another $_ hacker\n" }
    }
    grep {$_ =~ /^to_/ and defined *{ref($_[0])."::$_"}{CODE} }
    keys %{ref($_[0]).'::'};
} );

foreach (qw(to_xml to_html)) {
    $obj->dispatch($_);
}

-Nilson Santos F. Jr.


Mais detalhes sobre a lista de discussão Cascavel-pm