NAME

JavaScript::QuickJS - Run JavaScript via QuickJS in Perl

SYNOPSIS

Quick and dirty …

my $val = JavaScript::QuickJS->new()->eval( q<
    console.log("Hello, Perl!");
    [ "The", "last", "value", "is", "returned." ];
> );

DESCRIPTION

This library embeds Fabrice Bellard’s QuickJS engine into Perl. You can thus run JavaScript directly in your Perl programs.

This distribution includes QuickJS and builds it as part of building this module.

TYPE CONVERSION: JAVASCRIPT → PERL

This module converts returned values from JavaScript thus:

  • JS string primitives become character strings in Perl.

  • JS number & boolean primitives become corresponding Perl values.

  • JS null & undefined become Perl undef.

  • JS objects …

    • Arrays become Perl array references.

    • Functions trigger an exception. (TODO: Make those a Perl coderef.)

    • Other JS objects become Perl hash references.

TYPE CONVERSION: PERL → JAVASCRIPT

Generally speaking, it’s the inverse of JS → Perl, though of course since Perl doesn’t differentiate “numeric strings” from “numbers” there’s occasional ambiguity. In such cases, behavior is undefined; be sure to typecast in JavaScript accordingly!

  • Perl strings, numbers, & booleans become corresponding JavaScript primitives.

  • Perl undef becomes JS null.

  • Array & hash references become JavaScript arrays and “plain” objects.

  • Perl code references become JavaScript functions.

PLATFORM NOTES

Due to QuickJS limitations, Linux & macOS are the only platforms known to work “out-of-the-box”. Other POSIX OSes should work with some small tweaks to quickjs; see the compiler errors and quickjs.c for more details.

Pull requests to improve portability are welcome!

METHODS

For now only a static interface is provided:

$obj = CLASS->new()

Instantiates CLASS.

$obj = OBJ->std()

Enables (but does not import) QuickJS’s std module.

$obj = OBJ->os()

Like std() but for QuickJS’s os module.

$obj = OBJ->helpers()

Defines QuickJS’s “helpers”, e.g., console.log.

$VALUE = eval( $JS_CODE )

Comparable to running qjs -e '...'. Returns the last value from $JS_CODE.

Untrapped exception in JavaScript will be rethrown as Perl exceptions.

eval_module( $JS_CODE )

Runs $JS_CODE as a module, which enables ES6 module syntax. Note that no values can be returned directly in this mode of execution.

LICENSE & COPYRIGHT

Copyright 2019-2021 Gasper Software Consulting.

This library is licensed under the same terms as Perl itself.