Skip to content

Instantly share code, notes, and snippets.

@hknutzen
Last active January 1, 2022 15:05
Show Gist options
  • Save hknutzen/5a301cfbaaba321d66e6ee7cc46437ff to your computer and use it in GitHub Desktop.
Save hknutzen/5a301cfbaaba321d66e6ee7cc46437ff to your computer and use it in GitHub Desktop.
Assist in manual conversion of Perl code to Go (golang) code
#!/usr/bin/perl -p
use strict;
use warnings;
# Comment
if (s|^(\s*)#|$1//|) {
# convert variable names
s/[\$\%\@]([a-z][0-9a-z]*)/$1/g;
next;
}
s/^sub +(.*) *\{/func $1/;
# Parameter list, first
s/my *(\(.+\)) *= *\@_/$1 {/;
s/\b next \b/continue/x;
s/\b last \b/break/x;
s/ (\w+) \s+ if \s+ (.*) ; $/if $2 { $1 }/x;
s/ eq / == /g;
s/ ne / != /g;
s/[ ] print \( / fmt.Print(/x;
s/[ ] print [ ] ([^,"']+) [ ] ([^;]+) ; / fmt.Fprint($1, $2)/x;
s/[ ] print [ ] ([^;]+) ;/ fmt.Print($1)/x;
# Dereference, fixed key
s/->\{(\w+)}/.$1/g;
# Dereference, variable
s/->\{(\$\w+)}/[$1]/g;
# Hash access, fixed key
s/(\w)\{(\w+)}/$1.$2/g;
# Hash access, variable
s/(\w)\{(\$\w+)}/$1\[$2\]/g;
# scalar and hash variable
s/[\$\%]([a-z][0-9a-z]*)/$1/g;
# array variable
s/@(\w+)/$1/g;
# Strings
s/'([^']*)'/"$1"/g;
# semicolon
s/;$//;
s/for +my *(\w+) *\((.*)\) *\{/for _, $1 := range $2 {/;
s/elsif [ ]* \((.*)\) [ ]* \{/else if $1 {/x;
s/if [ ]* \((.*)\) [ ]* \{/if $1 {/x;
s/my [ ]* (\w+) [ ]+ =/$1 :=/x;
s/my [ ]* \((.+)\) [ ]+ =/$1 :=/x;
s/my [ ]+ (\w+)/var $1/x;
s/\b not \b/!/gx;
s/\b and \b/&&/gx;
s/\b or \b/||/gx;
# Snake case to camel case
s/_([a-z0-9]+)/\u$1/g;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment