I inherited a piece of code that I could not fully understand:
I know the red part is invoked by the blue part. But I don't quite understand what technique is this. And I don't understand exactly how those two BOLD RED lines work. Is there a specific TERM for this kind of implementation (such as call-back)? Is there a better way (more efficient and easier to understand) to implement this? Or is there an alternative way to implement this, though the alternative way could be less efficient but easier to understand?
Thank you very much for your help.
Code:
sub load_scenarios {
my ($tests) = @_;
my @results;
[COLOR=red]
my $add_instance = sub {
my ($name, $parent) = @_;[b]
my $instance = eval "my \$inst = new $name; \$${name}::parent = '$parent'; \$inst";
not $@ or die "Can't create instance for $name: $@\n";[/b]
push @results, $instance;
};
[/color]
foreach my $test (split /,/, $tests) {
# Some Implementation here
if ($test =~ m~^(.+)/(UserScenario\w+)$~) {
my ($subdir, $US) = ($1, $2);
load_module $test;[COLOR=blue]
&$add_instance($US, $subdir);[/color]
}
# Some Implementation here
}
return @results;
}
I know the red part is invoked by the blue part. But I don't quite understand what technique is this. And I don't understand exactly how those two BOLD RED lines work. Is there a specific TERM for this kind of implementation (such as call-back)? Is there a better way (more efficient and easier to understand) to implement this? Or is there an alternative way to implement this, though the alternative way could be less efficient but easier to understand?
Thank you very much for your help.