Skip to content

Instantly share code, notes, and snippets.

@pdl
Created June 22, 2015 09:21
Show Gist options
  • Save pdl/71306ec7a5f1e63fe280 to your computer and use it in GitHub Desktop.
Save pdl/71306ec7a5f1e63fe280 to your computer and use it in GitHub Desktop.
Convert perl scripts to javascript with the awesome power of regular expressions.
#!perl -w
=head1 NAME
pl2js.pl
=head1 DESCRIPTION
Attempts to convert perl scripts to javascript with the awesome power of regular expressions.
=head1 BUGS
This will (probably) not actually produce runnable js files. But it saves a lot of work converting some perl to js.
More useful if your perl code is well-indented to start with (consider using a source formatter first).
=head1 AUTHOR
Daniel Perrett C<< [email protected] >>
=cut
my $state;
while (my $sLine = <>)
{
$sLine =~ s`\s*=~[^/]+?s(/[^/]+/)([^/]*)/([a-z]*)`.replace($1, "$2", $3)`g;
$sLine =~ s`\s*=~[^/]+(/[^/]+/[a-z]*)`.match($1)`g;
$sLine =~ tr/$@%//d;
$sLine =~ s/(?!<\d)\.(?!\d)/+/g;
$sLine =~ s/::/./g;
if ($state->{'pod'})
{
$sLine =~ s/^=(?!cut)//g;
}
elsif ($sLine =~ s~^=(?!cut)~/*~)
{
$state->{'pod'} = 1;
}
if ($sLine =~ s~^=cut~*/~)
{
$state->{'pod'} = 0;
}
$sLine =~ s/^\s*package (.*?);/class $1:/g;
$sLine =~ s/^\s*use /import /g;
$sLine =~ s/^\bundef\b/undefined/g;
$sLine =~ s/^\beq\b/==/g;
$sLine =~ s/^\bge\b/>=/g;
$sLine =~ s/^\ble\b/=</g;
$sLine =~ s/^\bne\b/!=/g;
$sLine =~ s/^\bgt\b/>/g;
$sLine =~ s/^\blt\b/</g;
$sLine =~ s/\bor\b/||/g;
$sLine =~ s/\!defined/'undefined' == typeof/g;
$sLine =~ s/\!defined/'undefined' != typeof/g;
$sLine =~ s/\band\b/&&/g;
$sLine =~ s/\s+{(['"])(.*)\1}/.$2/g;
$sLine =~ s/\bsub ([\w]+)(?:\(([^)]+)\))?\s*\{?/function ()/g;
$sLine =~ s/\bmy\b/var/g;
$sLine =~ s/\bref\b/typeof/g;
$sLine =~ s/\bnot\b/!/g;
$sLine =~ s/\bnext\b/continue/g;
$sLine =~ s/->\{/./g;
$sLine =~ s/->\[/./g;
$sLine =~ s/->/./g;
$sLine =~ s~#~//~g;
print STDOUT $sLine;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment