Dynamic object name question

Dan Brook mr.daniel.brook at gmail.com
Thu Jun 30 21:18:17 BST 2011


On Thu, Jun 30, 2011 at 8:54 PM, Ian Knopke <ian.knopke at gmail.com> wrote:
> Hi everyone,
>
> I have a whole list of subobjects of the form:
>
> foreach my $t(@types){
>
>    if ($t eq 'first'){
>        Top::First->new(@args);
>    } elsif ($t eq 'second') {
>        Top::Second->new(@args);
>    } elsif
>     .... (add 20 more of these here)
>    };
> }
>
> Since the arguments coming in match the object names (except for case)
> there must be away to collapse this into something saner, but I don't
> know how. Does anyone have any advice?

You can just dispatch on a string e.g

  if(exists $possible_classes{$t}) {
    my $class = ucfirst $t;
    $class->new(@args);
  }

Filling in %possible_classes is left as an exercise to the reader.

Cheers,
Dan Brook



More information about the london.pm mailing list