Skip to content

Instantly share code, notes, and snippets.

@0racle
Last active October 12, 2022 12:17
Show Gist options
  • Save 0racle/4886aa61c1e4ded28eda1a6885a14c2c to your computer and use it in GitHub Desktop.
Save 0racle/4886aa61c1e4ded28eda1a6885a14c2c to your computer and use it in GitHub Desktop.
J in Raku (and Perl)
#!/usr/bin/env raku
use NativeCall;
class J is repr('CPointer') {
my constant $BIN = "/opt/j903/bin";
my constant $LIB = "$BIN/libj.so";
my constant $PRO = "$BIN/profile.ijs";
sub JInit () returns J is native($LIB) { * }
sub JDo (J, Str) returns uint32 is native($LIB) { * }
sub JGetR (J) returns Str is native($LIB) { * }
method new() {
my $j = JInit();
$j.do("0!:0<'$PRO'[BINPATH_z_=:'$BIN'[ARGV_z_=:''");
return $j;
}
method do(Str \c) {
JDo(self, c)
}
method getr() {
JGetR(self)
}
}
my $j = J.new;
loop {
my $expr = prompt(' ');
$j.do($expr); # returns 0 on success
print $j.getr();
}
@0racle
Copy link
Author

0racle commented Sep 15, 2022

For Windows users, you just need to modify the $BIN and $LIB, eg.

my constant $BIN = "C:/Program Files/J902/bin";
my constant $LIB = "$BIN/j.dll";

@0racle
Copy link
Author

0racle commented Sep 15, 2022

Including Perl because why not

use v5.36;
use warnings qw< FATAL all >;
use FFI::Platypus 2.00;

my $BIN = "/opt/j903/bin";
my $LIB = "$BIN/libj.so";
my $PRO = "$BIN/profile.ijs";

my $ffi = FFI::Platypus->new(api => 2);

$ffi->lib($LIB);
$ffi->attach(JInit => []                   => 'opaque');
$ffi->attach(JDo   => ['opaque', 'string'] => 'uint32');
$ffi->attach(JGetR => ['opaque']           => 'string');

my $j = JInit();
JDo($j, "0!:0<'$PRO'[BINPATH_z_=:'$BIN'[ARGV_z_=:''");

while (1) {
    print '   ';
    chomp(my $expr = readline());
    JDo($j, $expr);
    print JGetR($j);
}   

@0racle
Copy link
Author

0racle commented Oct 12, 2022

Now a Raku module: Inline::J

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment