Skip to content

Instantly share code, notes, and snippets.

@dheffx
Created February 16, 2018 16:51
Show Gist options
  • Save dheffx/8d07138be5b188cac9b1fcf6bef39ef9 to your computer and use it in GitHub Desktop.
Save dheffx/8d07138be5b188cac9b1fcf6bef39ef9 to your computer and use it in GitHub Desktop.
load a perl module into a javascript object
const proc = require('child_process')
const fs = require('fs')
function toJSON(filename) {
if (!compiles(filename)) {
throw new Error(filename + " does not compile in perl")
}
var jsObj = {}
try {
jsObj = perl2js(filename)
} catch (e) {
console.error("Failed to get object from " + filename)
}
return jsObj
}
function compiles(filename) {
try {
proc.execSync("perl -c " + filename)
} catch(e) {
return false
}
return true
}
function perl2js(filename) {
let code = 'use strict;use JSON;my $j=JSON->new;$j->allow_blessed(1);my $m="' + filename + '";require $m;my($p)=$m=~/^(.*?)\\.pm$/;my %s=();foreach my $var(keys %{$main::{$p."::"}}){my $g=$main::{$p."::"}{$var};if(${$g}){$s{$var}=${$g};}if(@{$g}){$s{$var}=[@{$g}];}if(%{$g}){$s{$var}={%{$g}};}}print $j->encode(\\%s)'
let result = proc.execSync("perl -e '" + code + "'")
return JSON.parse(result)
}
module.exports = {
toJSON: toJSON,
compiles: compiles
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment