Dynamic object name question

Dagfinn Ilmari Mannsåker ilmari at ilmari.org
Thu Jun 30 21:12:29 BST 2011


Ian Knopke <ian.knopke at gmail.com> writes:

> 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?

The invocant of a class method call does not have to be a literal
bareword, it can be any expression yielding a class name.

This means you can just define a function mapping the type to the class
name, and do:

   type_to_class_name($t)->new(@args);


-- 
ilmari
"A disappointingly low fraction of the human race is,
 at any given time, on fire." - Stig Sandbeck Mathisen


More information about the london.pm mailing list