Question

looping through classes using require

I have a number of plugin classes each of which have a method 'enable'. The following code works

unit class Top;
has $!rdp;
use Plugin::A;
use Plugin::B;
use Plugin::C;
submethod TWEAK {
  my $rdp := self.rdp;
  Plugin::A.new.enable($rdp);
  Plugin::B.new.enable($rdp);
  Plugin::C.new.enable($rdp);
}

The Plugin... classes are only used once to prepare $rdp, so I thought it would not matter whether the classes are looked up at run time or compile time.

I would like something of the form

for <A B C> {
  require ::("Plugin::$_");
  ::("Plugin::$_").new.enable($rdp)
}

I tried a variety of syntaxes, none of which work.

What would be a way to do this?

 3  66  3
1 Jan 1970

Solution

 3

TL;DR I've guessed at what you mean. I may be miles off, so this answer may be useless. Even if I guessed correctly, the answer may still be useless or hide problems that will surface in months/years to come because there are related open package loading issues that have not been fully debugged so any solution is just a workaround that happens to work in a given Rakudo release but may not work in the next.


My guess is that you're looking for something like this, which works in the Rakudo (from 2022) that's installed on glot.io at the time of writing this (2024):

for <A B C> {
  my $OK = True;
  require ::("Plugin::$_");
  CATCH { $OK = False; .resume }
  ::("Plugin::$_").new.enable($rdp) if $OK
}

I say "at a guess" because there are many ways to interpret what you wrote and you didn't provide a Minimal, Reproducible Example to help reduce the ambiguity.


My first key discovery as I researched your question was that using the try prefix on require seems to break Rakudo's anticipatory compile time work related to the package symbol corresponding to the package being required. So even if a package was found I couldn't then make use of the package symbol.


My second key discovery was there seem to be many related open issues in the Rakudo issue queue. For example: 1, 2, 3.

2024-07-05
raiph