Create module from content variable

I feel this might be a stupid question, or perhaps even one of those unexpectedly inflammatory ones; I'm still interested.

I have a configuration file that I read, and then based on the contents I create objects of different types. A good model would be a library catalog. Suppose I have packages (classes) of Books :: Historical, Books :: SciFi, Books :: Romance, etc. And config has hashes like

%book = (
  type => 'SciFi',
  name => 'Journey to the Center of the Earth',
  ...
);

When I read the conf file, I want to create objects of these types. I know I can do something like:

my $book_obj;
if ($book{'type'} eq 'SciFi') {
  $book_obj = Books::SciFi->new();
  #do stuff with $book_obj
} elsif ($book{'type'} eq 'Romance') { ...

but I was wondering if there is a way to do something more like

my $book_obj = Books::$book{'type'}->new();

so I don’t need to configure a huge if tree?

PS. , , , Books, , , .

+3
1

, , :

my $classname = 'Books::' . $book{type};
my $book_obj = $classname->new;

, LHS -> , .

, - :

my $book_obj = ${ \"Books::$book{type}" }->new;

.

+4

Source: https://habr.com/ru/post/1778516/


All Articles