Created
February 16, 2018 16:51
-
-
Save dheffx/8d07138be5b188cac9b1fcf6bef39ef9 to your computer and use it in GitHub Desktop.
load a perl module into a javascript object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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