Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl6: How to load a class module dynamically?

Tags:

oop

module

raku

How can I load a OO-style module dynamically?

#!/usr/bin/env perl6
use v6;

my $r = prompt ':';

if $r {
    require Text::CSV;          # Error:
    my $csv = Text::CSV.new;    # Could not find symbol '&CSV'
} else {
    require File::Temp <&tempfile>;
    my ( $filename , $filehandle ) = tempfile; # this works
}
like image 701
sid_com Avatar asked May 18 '16 08:05

sid_com


1 Answers

As explained in the perl6 doco here, you can dynamically load the module but;

To import symbols you must define them at compile time.

So, the code in the else clause works because of the explicit request to import <&tempfile>.

The closest thing to getting the code in the if clause to work that I can see is this (which is mostly taken from that earlier doco reference):

use v6.c ;

sub load-a-module($name) {
   require ::($name) ;
   my $instance = ::($name).new() ;
   return $instance ;
}

my $module = "Text::CSV" ;
my $csv = load-a-module $module ;
say $csv.WHAT ;
# say $csv.^methods ;   # if you really want to be convinced

# outputs: (CSV)
like image 177
Marty Avatar answered Jan 01 '23 08:01

Marty