-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperl2python
executable file
·1480 lines (1196 loc) · 55.7 KB
/
perl2python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Rudimentary Perl -> Python translation assistant.
# Written 2011-09, by Steven J. DeRose.
#
import sys
import argparse
import re
import time
import datetime
from typing import IO
__metadata__ = {
"title" : "perl2python",
"description" : "Rudimentary Perl -> Python translation assistant.",
"rightsHolder" : "Steven J. DeRose",
"creator" : "http://viaf.org/viaf/50334488",
"type" : "http://purl.org/dc/dcmitype/Software",
"language" : "Python 3.7",
"created" : "2011-09",
"modified" : "2021-06-24",
"publisher" : "http://github.com/sderose",
"license" : "https://creativecommons.org/licenses/by-sa/3.0/"
}
__version__ = __metadata__["modified"]
descr = """
=Usage=
perl2python [options] file
A rudimentary `Perl` to '''Python''' translation assistant.
This script does not do a complete translation, but does handle many of
the tedious, repetitive, simple parts. Run some Perl code through
it, and then finish the translation by hand. You'll still have a lot of
small changes to make, but you won't have to remove thousands of semicolons,
change `{` to ''':''', take `$@%` off of variables
(leaving `sprintf("...%..."...)` intact),
rename functions (`lc`() to '''lower'''(), etc.).
''Note'': This mainly applies a long list of regex changes, line by line.
''Note'': A few errors that can be caught, will be reported inline with
comments starting `## PROBLEM`.
=head2 Some things this script will do (mostly)
* Change the shebang (`#!`) line.
* Put in '''import''' lines for common packages.
* Convert loops and conditions:
if/elsif/else
postfix `if` and `unless`;
`(expr) ? y:z`;
`(expr) && action`;
`next` to '''continue''';
`last` to '''break''';
`for (my x=y; x<z; z++)` and similar simple cases
and so on.
* Fix most `{}`, etc.
* Discard `my/our/local`, and the type-characters on variables.
* Rearrange `=~` and `!~` into Python '''re''' package forms.
Even change them to lstrip() and rstrip() when appropriate.
* Change regex matches to save the Python match object as '''mat''',
add $1 etc. to mat.group(1) etc. These will sometimes need manual cleanup.
* Change $_ to $dftVar (more will typically be needed since '''$_'''
is set automatically, and that doesn't translate easily).
* Convert `Getopt::Long` to Python's '''argparse'''.
However, there are some limitations, including:
** one argument definition per line (synonyms are handled, though).
** If you create a hash of the argument definitions as a separate variable,
instead of just passing them all as arguments to `getOpt::Long()`, then you
must specify the variabe name on the '''--getOptVar''' option to this script.
** Anonymous `sub`s for the action part don't work.
** Entries for '''--help''' and/or '''--version''' will be deleted, since
Python gives you those for free.
** Won't copy option-variable declarations from earlier (for
defaults), into the '''default''' paremeter of '''add_argument''', or
documentation from Perldoc into the '''help''' parameter. It does create
an empty '''help''' parameter, however.
** Won't do anything special for Python argparse types
that aren't known to GetOpt (files, complex numbers, etc.).
* Move Perldoc information into a Python triple-quoted string to
keep it out of the way. Nothing between `=pod` and `=cut` is changed.
* Change `sub` to '''def''', and mostly adjust the parameter declarations
'''if''' you did them like:
sub foo {
my ($x, $myFoo, $zorch) = @_;
...}
* Convert a wide variety of operators, such as:
string and numeric comparisons (including `< <=` >> and `cmp`),
`.`, `x` (for strings),
`||`, `&&`,
`++`, `--`, `+=`, `-=`, `*+`, `/-`,
`!`, `< =` >>,
`-f` and other file predicates,
simple uses of ternary '?'
and so on.
* Turn `substr(s,start,length)` into '''s[start:start+length]'''.
Will only work if there are no commas embedded within the arguments.
* Clean up some casts, lookups, and references like @{x}, $x->{y},
@$x, %@x, etc.
* Convert rudimentary file I/O calls.
* Rename common functions, such as `int` to '''floor''',
`lc` to '''lower''', `push` to '''append''', `sort` to '''sorted''', etc.
Change `$ENV{}` to '''os.environ[]'''.
* Turn `print` and `warn` into appropriate Python code.
= item * Break variables out of quoted strings, and add '''str'''()
around them.
Doesn't do a very good job of it yet (mostly only works on full-line strings).
This is improving, along with support for various Perl quote-types.
* Change package-name separator from `::` to '''.'''. Change `package`
keyword to '''class'''. Change `sub new` to '''def __init__'''.
Does not yet change assignments to the object hash in new(), to make real
instance variables.
=head2 Some things this script will NOT do
* Convert perl ref() calls to Python type().
* Doesn't move functions so they're defined before used.
* Doesn't handle regexes using other than `/` as delimiter.
* Doesn't support `do { }`.
* Doesn't do much to move assignments outside of `if` conditions.
* Doesn't introduce or normalize indentation, other than
expand tabs (default width: 4, see '''--tabs''').
Use an editor or pretty-printer if needed before using this script.
* No support for most Perl reserved variables:
`$/`, `$\\`, `$``, `$&`, `$'`, `$_[]`, etc.
* Some, but incomplete, support for Perl references:
`$self`, `\\$`, `\\@`, `\\%`, `@$`, `%$`, etc.
* Doesn't catch `x` operators with anything but a quoted string before.
* Doesn't do much with packages and references.
Doesn't do anything at all about packages you `use`.
* Doesn't indent '''def''' within classes.
* Weak support for inline subs (such as for `sort` or `Getopt` actions).
`grep`, `oct`, `chop`, `splice`, `lcfirst`, `ucfirst`,
`tr///`, `study`, `pack`, `unpack`, `values`, `map`,
`eof`, `printf`, `readline`, `stat`, `sprintf`,
`binmode`, `opendir`, `readdir`,
`redo`, `wantarray`, `caller`, `use`, `require`,
`tie`,
* Doesn't handle `exec`, `fork`, etc.
* Per filehandle special variables
* '' $| ''
If set to nonzero, forces a flush after every write or print
* '' $% ''
Current page number
* '' $= ''
Current page length
* '' $- ''
Number of lines left on the page
* '' $~ ''
Name of the current report format
* '' $^ '' Name of the current top-of-page format
* Local special variables
* '' $1..$9 '' Contains the subpattern from the corresponding set of
parentheses in the last pattern matched. I<Renamed to `mat.group(n)`,
because regex matches are changed to assign to `mat`.
* '' $& ''
Contains the string matched by the last pattern match
* '' $` ''
The string preceding whatever was matched by the last pattern match,
not counting patterns matched in nested blocks that have been exited already.
* '' $' ''
The string following whatever was matched by the last pattern match,
not counting patterns matched in nested blockes that have been exited already.
* '' $+ ''
the last bracket matched by the last search pattern. This is useful
if you don't know which of a set of alternative patterns matched.
* Global special variables
* '' $_ '' The default input and pattern-searching space.
'''Renamed to dftVar'''
* '' $. ''
The current input line number of the last filehandle that was read.
* '' $/ ''
The input record separator, newline by default.
* '' $\\ ''
The output record separator for the print operator.
* '' $, ''
The output field separator for the print operator.
* '' $" '' This is similar to $, except that it applies to array
values interpolated into a double-quoted string (or similar interpreted
string). Default is space.
* '' $# ''
The output format for numbers display via the print operator.
* '' $$ ''
The process number of the Perl running this script.
* '' $? '' The status returned by the last pipe close, backtick(``)
command or system operator.
* '' $* '' Set to 1 for multi-line matching within a string, 0 to
tell Perl that it can assume that strings contain a single line, for
the purpose of optimizing pattern matches. Default is 0
* '' $0 ''
Contains the name of the file containing the Perl script being executed.
* '' $[ ''
The index of the first element in an array, and of the first character
in a substring.
* '' $] '' The first part of the string printed out when you say perl -v.
* '' $; '' The subscript separator for multi-dimensional array emulation.
* '' $! ''
If used in a numeric context, yields the current value of errno, with all
the usual caveats.
* '' $@ '' The Perl syntax error or routine error message from the
last eval, do-FILE, or require command.
=head2 How to make Perl code convert better
* Use consistent whitespace and indentation.
* Break up complicated embedded constructions into more, simpler
ones. For example, don't nest `?`, `substr`(), etc.
* Always break after the `{` that starts a block,
before the `}` that ends one, and after `;` (except in `for`).
* Use function parentheses.
* Always copy `sub` arguments from `@_` to named variables to use,
on the line right after the `sub name {`.
my ($x, $y, $z) = @_;
* Use `< () `> around all conditions, even in shortcuts
like `(cond) && action;`.
=Options=
=over
* ''--getOptVar''
If you create a hash of the argument definitions as a separate variable,
instead of just passing them all as arguments to `getOpt::Long()`, then you
must specify the variabe name on this option.
* ''--quiet'' OR ''-q''
Suppress most messages.
* ''--singleQuoteOptions''
Declare long option names to start with "-" (default is to use "--").
* ''--tabs'' '''n'''
Expand tabs assuming tab-stops are every '''n''' columns (default: 4).
* ''--trace''
Give lots of detail on regex operations. See also '''--verbose'''.
* ''--verbose''
Add more messages (repeatable). See also '''--trace'''.
* ''--version''
Show version info and exit.
=Known Bugs and Limitations / To do list=
Many.
Major:
Fix argparse handling to handle "my %getOptHash = ("...
Option to use my newer argparse (ref MarkuphelpFormatter, use flag options)
Problems:
with tests of substr() vs. 0, change to try...except
handle multi-line quotes better (esp. qw)
Turns some line-final '{' that open hashes, into ':'.
{} left in {z} ??
do *something* with $/, etc. (now loses the '$')
move file arg for print (r'\\bprint\\s+(\\w+)\\s+')
Flow constructs:
toasts 'if' even if only got ==, not =
sometimes fails to indent 'if'
swap "if (x = ...)" to "x = ...\\nif(x)" in general?
leaves line-final ' +' on some 'if's
Gets confused on some if/for w/ block on same line.
Sorting:
sort keys x (lose 'keys')
sorted keys ... -> sorted(foo, key=foo.get, cmp=compfunction)
sort(a,b) convention
Constructors:
self{\\w+} goes to [], should go to .
self inits in new() should create items, not hash entries.
self\\[(\\w+)\\] -> self.\\1
constructors shouldn't return 'self'.
new -> __init__; class -> self
Finish -getOptVar.
regexes:
always puts in mat = re.sub... even inside an if.
changes to put in match instead of sub don't seem to work.
/= {/ vs. { for open-block vs. { in regex -- breaks when shouldn't
backslashes the apostrophes around regexes
re.sub loses RHS, at least if null
printf/sprintf:
turns %f in sprint to 'flt'??
loses '%' in sprintf format strings.
strings:
..." . $x . "... -> '%s'...%(x)
cosmetic:
doesn't delete all the ";", and leaves blank lines and ";"-only lines
space before final ':'
extra space after 'not'
indent 'sub' when after 'package'
=Related commands=
`perl`, `python`.
LLMs have gotten fairly good at this since.
=History=
* Written 2011-09, by Steven J. DeRose.
* 2011-09-19ff sjd: Fixed:
toasted indentation (expandTabs?
break lines at ";" early on?
how to get at $1 etc. after =~ s///?
shift @foo to foo.shift()
sys.stdout.isatty()
-- is confused; only change after \\w?
spurious insertion of 1-os.path.getsize from ---s
? operator: create whole 'if' with newlines
ditch 'new'
($x = $y) =~ ...
XML tags in quotes turn into readline(tag)
int goes to floor when it shouldn't (like in argparse)
no type=string, action='store_true'
for my $k (keys %foo) -> for k, v in foo ??
spurious r""?
class colon
`...`
newline at end of printed strings
getopts version
strip // from around regexes in split
don't nuke % inside sprintf()
Separate GetOpt conversion, so we can accumulate list of var names
W/ GetOpt, deal with the prior inits.
accumulate the options vars? use those vars later
Handle shebang line at top, outside loop.
Split and complile changes before main loop.
(x]
\\$ \\@ \\%
x[y]->[z]
[@%]\\{.*?\\}
* 2011-10-17 sjd: tweaks
* 2012-01-10 sjd: +=, -=, *=, /=, .=, ->, (\\s+, ; alone, preserve !=, ....
* 2012-01-12 sjd: Various regex tweaks for if, for, substr, =~, -->, ternary ?.
Major upgrades to GetOpt() handling. Clean up mainline logic. "+" options.
* 2012-01-24 sjd: Major rewrite to handleGetOpt: Handle inverted options,
set dest when needed, do aliases better, modularize.
* 2012-01-31 sjd: Minor tweaks. Add helpMessages. Fix list ops.
Remove part-line comments early, then replace at end.
* 2014-04-25 Misc. clean-up. Code regexes as [ lhs, rhs ] instead of a string.
Don't turn regex /g into flags="g" instead of nothing (or count=0)
* 2014-05-14: Better handling of @{$x}, for, while($x = readline()),...
* 2021-06-24: General update, fixes, add POD-to-MarkDown, better error
reporting and change tracing.
=Ownership=
Copyright 2011 by Steven J. DeRose. This work is licensed under a Creative Commons
Attribution-Share Alike 3.0 Unported License. For further information on
this license, see L<http://creativecommons.org/licenses/by-sa/3.0/].
For the most recent version, see L<http://www.derose.net/steve/utilities/>
or [https://www.github.com/sderose/utilities].
=Options=
"""
args = None
def info(msg):
sys.stderr.write("Info: %s\n" % (msg))
def warning(msg):
sys.stderr.write("Warning: %s\n" % (msg))
def error(msg):
sys.stderr.write("Error: %s\n" % (msg))
def flag(msg): # Report and put msg inline
sys.stderr.write("Error: %s\n" % (msg))
print("### ERROR: %s" % (msg))
def fatal(msg):
sys.stderr.write("Fatal: %s\n" % (msg))
sys.exit()
delta = chr(0x0394)
###############################################################################
# Should rename any Perl variables with these names (not used yet)
#
reservedWords = [
"and", "assert", "break", "class", "continue",
"def", "del", "elif", "else", "except",
"exec", "finally", "for", "from", "global",
"if", "import", "in", "is", "lambda",
"not", "or", "pass", "print", "raise",
"return", "try", "while",
"Data", "Float", "Int", "Numeric", "Oxphys",
"array", "close", "float", "int", "input",
"open", "range", "type", "write", "zeros",
"acos", "asin", "atan", "cos", "e",
"exp", "fabs", "floor", "log", "log10",
"pi", "sin", "sqrt", "tan"
]
reservedExpr = r"\$(" + "|".join(reservedWords) + r")\b"
###############################################################################
# Default help messages to supply for common GetOptLong option names.
#
helpMessages = {
"delim" : "Field separator.",
"quote" : "Field quoting character.",
"clean" : "Recode control characters for readability.",
"noclean" : "Leave control characters as-is.",
"color" : "Colorize the output.",
"nocolor" : "Don't colorize the output.",
"fields" : "Names/numbers of fields to display (repeatable).",
"files" : "Path(s) to input data.",
"iencoding" : "Set the input character set (not yet).",
"ilineends" : "Style of line-ends to use (M|U|D)",
"numberFields" : "Show field numbers as well as field names.",
"nonumberFields" : "Don't show field numbers as well as field names.",
"pause" : "Pause after each record (unfinished).",
"nopause" : "",
"quiet" : "Suppress most messages.",
"noquiet" : "",
"verbose" : "Add more messages (repeatable).",
"width" : "How many columns to leave for field labels.",
#
# For CSV package
#
"comment" : "Ignore records beginning with this string.",
#"delim" : "Field separator (default: tab).",
"escape" : "Character to escape quotes inside quotes.",
"header" : "There is a header record, providing field names",
"noheader" : "There is NO header record, providing field names",
"nlInQuotes" : "Allow newlines within quoted fields.",
"nonlInQuotes" : "Do not allow newlines within quoted fields.",
#"quote" : "Character used to quote field values (default: '\"').",
"qdouble" : "Allow a quote inside quotes via '\"\"'.",
"noqdouble" : "Do not allow a quote inside quotes via '\"\"'.",
"stripFields" : "Remove leading/trailing whitespace from fields.",
"nostripFields" : "Do not remove leading/trailing whitespace from fields.",
"stripRecords" : "Remove leading/trailing whitespace from records.",
"nostripRecords" : "Do not remove leading/trailing whitespace from records."
}
###############################################################################
# An ordered list of regex changes.
#
changes = [
# Remove trailing spaces to simplify many later regexes
[ r"\s+$/", r"" ],
[ r"^(\s*)([^#]*?;)\s*([^\s#])", r"\1\2;\n\1\3" ], # ????
###########################################################################
# Packages and inits
#
[ r"^\s*\buse strict\b",
r"import sys\nimport os\nimport re\nimport subprocess" +
r"\nimport string\n" + r"import math\n" ],
[ r"^\s*\buse Getopt\.Long", r"import argparse" ],
[ r"^\s*\buse ", r"import " ],
###########################################################################
# Regex match/change
# (maybe also change simple cases to lstrip/rstrip)
# (these are not careful enough about single/double/other quotes)
#
[ r"^(\s*)\(\$(\w+) = \$(\w+)\) =~ s", r"\1\2 = \3\n\1\1 =~ s" ],
# =~ m// and !~ m// (and assign to 'mat' in case later code uses \1)
#
[ r"\$(\w+)\s*=~\s*m/^([^/]+)/g\b", r"mat = re.match(r'\2', \1)" ],
[ r"\$(\w+)\s*=~\s*m/^([^/]+)/(\w+)", r"mat = re.match(r'\2', \1, flags=\"\3\")" ],
[ r"\$(\w+)\s*=~\s*m/^([^/]+)/", r"mat = re.match(r'\2', \1)" ],
[ r"\$(\w+)\s*=~\s*m/([^/]+)/g\b", r"mat = re.search(r'\2', \1, count=0)" ],
[ r"\$(\w+)\s*=~\s*m/([^/]+)/(\w+)", r"mat = re.search(r'\2', \1, flags=\"\3\")" ],
[ r"\$(\w+)\s*=~\s*m/([^/]+)/", r"mat = re.search(r'\2', \1)" ],
[ r"\$(\w+)\s*!~\s*m/([^/]+)/(\w+)", r"not re.search(r'\2', \1, flags=\"\3\")" ],
[ r"\$(\w+)\s*!~\s*m/([^/]+)/", r"not re.search(r'\2', \1)" ],
# =~ s/// and remember that Perl changes the string in place...
#
[ r"\$(\w+)\s*=~\s*s/\^\\s+//", r"\1 = \1.lstrip()" ],
[ r"\$(\w+)\s*=~\s*s/\\s+\$//", r"\1 = \1.rstrip()" ],
[ r"\$(\w+)\s*=~\s*s/([^/]+)/([^/]+)/(.*)", r'\1 = re.sub(r\'\2\', \3, \1, flags="\4")' ],
[ r"\$(\w+)\s*=~\s*s/([^/]+)/([^/]+)/", r'\1 = re.sub(r\'\2\', \3, \1)' ],
###########################################################################
# Flow of control
#
[ r"^(\s*)if \((\s*my\s+)?\$(\w+)\s*=\s*(.*)\)\s*{",
r"\1\3 = \4\n\1if (\3):" ],
# if
#
[ r"(\bif\s*\([^\)]*\))\s*{", r"\1:" ],
[ r"^(\s*)if\s*(\([^{}]*\))\s*{(\s*\S+)?\s*$", r"\1if \2:\n\1 \3" ],
[ r"\belsif\s*(\S.*)\s*{", r"elif \1:" ],
[ r"\belse\s*{", r"else:" ],
[ r"^(\s*)(.*)\bunless\s*(\(.*?\));", r"\1if (not \3):\n\1 \2" ],
[ r"^(\s*)(\S.+?) unless (\(.*\));", r"\1if (not \3):\n\1 \2" ],
[ r"^(\s*)(\S.+?) if (\(.*\));", r"\1if (\3):\n\1 \2" ],
# for
#
[ r"\bfor\s*\((my\s+)?\$(\w+)\s*=\s*([^;]*);" +
r"\s*\$\w+\s*<=?\s*([^;]*);" +
r"\s*\$\w+\s*(\+\+|\+=\s*1)\)\s*{",
r"for \2 in range([\3,\4]):" ],
[ r"\bfor\s*\((my\s+)?\$(\w+)=(\d+);\s*\$\2\s*<=\s*(.*?);\s*\$\2\+\+\) {",
r"for \2 in (range(\3,\4+1)):" ],
[ r"\bfor (my )?(\S+) \(keys (.*)\) {", r"for \2 in (\3):" ],
[ r"\bfor (my )?(\S+) \((.*)\) {", r"for \2 in (\3):" ],
[ r"\bforeach\s*(my\s+)?(\w+)\s*(.*?)", r"for \2 in (\3)" ],
# other flow of control
#
[ r"\bwhile (\([^{]+\)) {", r"while (\1):" ],
[ r"\bnext\b", r"continue" ],
[ r"\blast\b", r"break" ],
[ r"\bexit\b", r"sys.exit" ],
# Short-cut AND and OR
#
[ r"^(\s*)(\(.*?\)) &&\s*", r"\1if \2:\n\1 " ],
[ r"^(\s*)(\(.*?\)) \|\|\s*", r"\1if (not \2):\n\1 " ],
# Ternary ?... (not really right...).
#
[ r"^(\s*)(my\s+)([$@%]\w+)\s*=\s*(\(.*?\))\s*\?(.*)\s*:\s*(.*);",
r"\1if \4:\n\1 \3 = \5\n\1else:\n\1 \3 = \6" ],
[ r"\^(\s*)\((.*?)\) \|\| ", r"\1if (not \2):\n\1 " ],
###########################################################################
# Functions
#
[ r"\bsort keys ([$\w+]+|%{[$\w+]+})", r"sorted(\1, key=\1.get)" ],
[ r"\bsort\b", r"sorted" ],
[ r"\bint\(\b", r"floor(" ],
[ r"\bdelete\b", r"del" ],
[ r"\bundef\b", r"None" ],
#[ r"\bpackage (.*);", r"class \1:" ],
[ r"\bbless\b", r"# bless" ],
[ r"\bdefined\b", r"None == " ],
[ r"= new ", r"= " ],
[ r"sub new ", r" def __init__()" ],
[ r"sub (\w+::)+(\w+) ", r" def \2" ],
[ r"\blc\s*\(", r" lower(" ],
[ r"\buc\s*\(", r" upper(" ],
[ r"\blength\b\(", r"len\(" ],
[ r'\bjoin\(("[^"]"),\s*', r'\1.join(' ],
[ r'\bjoin\((\'[^\']\'),\s*', r'\1.join(' ],
[ r"\bchomp\s+([\$\w]+)", r'\1 = strip(\1, "\n\r")' ], # ???
[ r"\bsplit\(/(.*)/", r' re.split(\'\1\'' ],
[ r"\bsubstr\(([^,]*?),([^,\)]*)\)", r" \1[\2:]" ], # ???
[ r"\bsubstr\(([^,]*?),([^,]+?),([^,]*?)\)",
r" \1[\2:\2+\3]" ],
[ r"\breverse\s*\(\$(\w+)\)", r" \1[::-1]" ],
[ r"^(.*)\btranslate\s*\((.*?),(.*?),(.*?)\)",
r"\1mytrans = maketrans(\3,\4)\n\1translate(\2,mytrans)" ],
[ r"\bhex\s*\(", r" fromhex(" ],
[ r"\btime\s*\(", r" gmtime(" ],
[ r"\bopen\s*\(?(\w+),\s*>(.*?)\)?", r'\1 = open(\2, "w");' ],
[ r"\bopen\s*\(?(\w+),\s*<(.*?)\)?", r'\1 = open(\2, "r");' ],
[ r"\bclose\s*\(?(\w+)\)?", r"\1.close()" ],
[ r'\bsprintf\(("[^"]),\s*', r'\1.format(' ],
[ r'\bprintf\(("[^"]),\s*', r'print(\1 % (' ],
# Stack functions
#
[ r"\bpop @(\w+)\b", r"\1.pop()" ],
[ r"\bpush @(\w+)\s*,\s*(.+?)(\b|$|;)", r"\1.append(\2)" ],
[ r"\bshift @(\w+)\b", r"\1.pop(0)" ],
[ r"\bunshift @(\w+),\s*(.+?)\b", r"\1.insert(0,\2)" ],
[ r"\bpop @{$(\w+)}\b", r"\1.pop" ],
[ r"\bpush @{$(\w+)}\s*,\s*(.+?)(\b|$|;)", r"\1.append(\2)" ],
[ r"\bshift @{$(\w+)}\b", r"\1.pop(0)" ],
[ r"\bunshift @{$(\w+)},\s*(.+?)\b", r"\1.insert(0, \2)" ],
###########################################################################
# Variable and subroutine definitions
# (multi-line array/hash assignments don't have their () fixed)
# Should discard 'my' etc. earlier??
#
[ r"^sub (.*)\s*{", r"def \1(" ], # sub
[ r"^(\s*)(my|local|our)\s+\$(\w+);", r"\1\2 = None" ], # $x
[ r"^(\s*)(my|local|our)\s+\@(\w+\s*)=\s*\(\);", r"\1\2 = []" ], # @x = ()
[ r"^(\s*)(my|local|our)\s+\%(\w+\s*)=\s*\(\);", r"\1\2 = {}" ], # %x = ()
[ r"^(\s*)my \(\s*(.*)\)\s*=\s*@_;", r"\1\2):" ], # my (...)
[ r"^\s*(my|local|our)\s+@(.*?)\s*=\((.*)\)$", r"\1 = array([\2])" ], # @x = array()
[ r"^\s*(my|local|our)\s+@(.*?)\s*=\((.*)$", r"\1 = array([\2" ], #
[ r"^\s*(my|local|our)\s+%(.*?)\s*=\((.*)\)$", r"\1 = {\2\}" ], # %x = {...}
[ r"^\s*(my|local|our)\s+%(.*?)\s*=\((.*)$", r"\1 = {\2" ], #
[ r"\b(my|local|our)\s+[@%\$]", r"" ], # $x @x %x
###########################################################################
# Reserved variables, system stuff, etc.
# Special variable are not done yet. See doc.
#
[ r"\$ENV\{(.*?)\}", r'os.environ["\1"]' ], #
[ r"\b[$@]ARGV", r"sys.argv" ], #
[ r"\$_ ", r"$dftVar " ], #
[ r"\$(\d)\b", r"mat.group(\1)" ], #
[ r"= `(\w+) (.*)`", r'= exec_command(["\1", "\2"])' ],
[ r"\bscalar[ \(]+", r"len(" ], #
[ r'\bprint[ (](.*?)\\n"\)?;', r'print(\1")' ], #
[ r"\bprint[ (](.*?)\)?;", r"print(\1)" ], #
# I tend to start a new line after 'die' and 'warn' keywords,
# so insert the "(". Still have to insert the ")" manually.
#
[ r"\b(die|warn|print)\s*$", r"\1(" ], #
# See also under handling of quoted lines....
#
[ r"^(\s*)\bdie\b(.*);", r"\1print(\2) # DIE\n\1 exit(0)" ],
[ r"\bwarn\s*\(?(.*)\)?\s*;", r"sys.stderr.write(\1)" ], #
[ r"\bwarn\s*$", r"sys.stderr.write(" ], #
[ r"\$self->\{([^{}]+)\}", r"self.\1" ], #
[ r"->", r"." ], #
[ r"\$(\w+)(\.)?\{([^{}]+)\}", r"\1[\3]" ], #
###########################################################################
# File operations
# (happens *after* stripping variable prefix chars [$@%])
#
[ r"(?<!w)-r\s+\$?([^()]+)", r"os.access(\1,os.R_OK)" ], # -w...
[ r"(?<!w)-w\s+\$?([^()]+)", r"os.access(\1,os.W_OK)" ],
[ r"(?<!w)-x\s+\$?([^()]+)", r"os.access(\1,os.X_OK)" ],
[ r"(?<!w)-e\s+\$?([^()]+)", r"os.path.exists(\1)" ],
[ r"(?<!w)-z\s+\$?([^()]+)", r"os.path.getsize(\1)>0" ],
[ r"(?<!w)-s\s+\$?([^()]+)", r"os.path.getsize(\1)" ],
[ r"(?<!w)-d\s+\$?([^()]+)", r"os.path.isdir(\1)" ],
[ r"(?<!w)-f\s+\$?([^()]+)", r"os.path.isfile(\1)" ],
[ r"(?<!w)-t\s+\$?([^()]+)", r"\1.isatty()" ],
[ r"\bSTDIN\b", r"sys.stdin" ],
[ r"\bSTDOUT\b", r"sys.stdout" ],
[ r"\bSTDERR\b", r"sys.stderr" ],
# <...> for reading input file
# Would be nice to pull this out when it's in an '[el]if'...
[ r"^(\s+)while\s*\((\w+)\s*=\s*<(\$?\w+)>\)?\s*{",
r"\1while(1):\n \1\2 = \3.readline()\n \1if (not \1): break" ],
[ r"\s*=\s*<(\$\w+|[A-Z]+)>", r"= \1.readline()" ],
###########################################################################
# Operators
#
# r"\s*%(\s+|$)", r"mod " ], ###
[ r"=>", r":" ], # =>
[ r"\s*\{(\s*#.*)$", r":\1" ], # { # comment
[ r"\s*\{\s*$", r":" ], # {
[ r"\s*\}(\s*#.*)$", r"\1" ], # } # comment
[ r"\s*\}\s*$", r"" ], # }
[ r"\s+&&(\s+|$)", r" and " ], # &&
[ r"(^|\s+)\|\|(\s+|$)", r" or " ], # ||
[ r"\.\.", r":" ], # range
[ r"::", r"." ], # package-sep
[ r'"\s+\.\s+\$', r'" + ' ], # concat
[ r'(\w)\s+\.\s+(["$])', r'"\1 + \2' ], #
[ r"\+\+", r" += 1" ], # ++
[ r"([a-zA-Z])\-\-([^>])", r"\1 -= 1\2" ], # -- but not -->
# r"\b(\S)\s*([-+*/])=", r"\1 = \1 \2" ], ### += -= *= /=
[ r" \.=(\s+|$)", r" += " ], # .= (concat)
[ r" \.(\s+|$)", r" + " ], # . (concat)
[ r'" x ', r' " * ' ], # "foo" x 7
[ r"(\$\w+) x ", r' "\1 * ' ], # $var x 3
[ r"%\$|@\$", r"" ], # cast-from-ref
[ r"\\[$@%]", r"" ], # cast-to-ref
[ R"\]->\[", r"][" ],
# Operators: comparison
#
[ r"(\S+)\s+<=>\s+(\S+)", r" cmp(\1,\2)" ], # cmp() not in Python 3
[ r"(\S+)\s+cmp\s+(\S+)", r" cmp(\1,\2)" ],
[ r" lt ", r" < " ],
[ r" le ", r" <= " ],
[ r" gt ", r" > " ],
[ r" ge ", r" >= " ],
[ r" eq ", r" == " ],
[ r" ne ", r" != " ],
[ r"([( ])!([^=~])", r" \1not \2" ],
###########################################################################
# Weird cleanup -- these were added to clean up problems discovered.
# Deleting some of them would be nice.
#
[ r'(\("[^"]*\')[$@%](\w+)(\'[^"]*")', r'\1" + \2 + "\3' ],
[ r";\s*}:\s*$", r"" ], # ???
[ r"^(\s*)(if\s*\(.*\))\s*{\s*(}\s*)$", r"\1\2:" ], # if ()
[ r"^(\s*)(if\b.*:)\s*(\S)", r"\1\2:\n\1 \3" ],
[ r"@\{(.*?)\}", r"\1" ],
[ r"@\[(.*?)\]", r"\1" ],
[ r"[$@%]([A-Za-z]+)", r"\1" ], # var names
# r";\s*(#.*)$", r" \1" ], ###
# r"([^#\s])\s\s+", r"\1 " ], ###
[ r"\)\s+:\s*$", r"):" ],
# r"[\(\[\{]\s+", r"(" ], ###
[ r"\.\[", r"[" ],
# r"\.\{", r"[" ], ###
[ r"^(\s*def .*)\s*\(\s+", r"\1(" ],
[ r"\s*;\s*$", r"" ], # leftover ";"
[ r"^\s*;\s*", r"" ],
# Round margins to multiple of 4
#
[ r"(\S) +=", r"\1 =" ],
[ r"^ (\S)", r"\1" ],
[ r"^ (\S)", r" \1" ],
[ r"^ (\S)", r" \1" ],
[ r"\(\s+", r"(" ],
[ r"\bif +", r"if " ],
[ r"\bnot +", r"not " ],
] # END OF CHANGE LIST
###############################################################################
# Enabled via --specialVars
#
TODO = "#TOTO "
specialVarChanges = [
[ r"\$\|\b", TODO+r"\1#" ], # If set to nonzero, forces flushes
[ r"\$%\b", TODO+r"\1#" ], # Current page number
[ r"\$=\b", TODO+r"\1#" ], # Current page length
[ r"\$-\b", TODO+r"\1#" ], # Number of lines left on the page
[ r"\$~\b", TODO+r"\1#" ], # Name of the current report format
[ r"\$\^\b", TODO+r"\1#" ], # Name of the current top-of-page format
# [ r"\$\d\b", TODO+r"\1#" ], # Subpattern from last match. I<Renamed to `mat.group(n)`
[ r"\$&\b", TODO+r"\1#" ], # String matched by the last pattern match
[ r"\$`\b", TODO+r"\1#" ], # String preceding whatever was matched
[ r"\$'\b", TODO+r"\1#" ], # String following whatever was matched
[ r"\$\+\b", TODO+r"\1#" ], # Last bracket matched by last pattern
[ r"\$_\b", TODO+r"\1#" ], # Default input and pattern space. '''Renamed to dftVar'''
[ r"\$\.\b", TODO+r"\1#" ], # Current line number of the last filehandle read
[ r"\$/\b", TODO+r"\1#" ], # Input record separator
[ r"\$\b", TODO+r"\1#" ], # Output record separator for print
[ r"\$,\b", TODO+r"\1#" ], # Output field separator for print
[ r'\$"\b', TODO+r"\1#" ], # Similar to $, except for array values in a "string"
[ r"\$#\b", TODO+r"\1#" ], # Output format for numbers via print.
[ r"\$\$\b", TODO+r"\1#" ], # Process number of the Perl running this script
[ r"\$\?\b", TODO+r"\1#" ], # Status of last pipe close, backtick(``) or system.
[ r"\$\*\b", TODO+r"\1#" ], # 1 for multi-line matching within a string
[ r"\$0\b", TODO+r"\1#" ], # Name of the Perl script being executed
[ r"\$\[\b", TODO+r"\1#" ], # Index of first element in array; character in string
[ r"\$\]\b", TODO+r"\1#" ], # First part of perl -v
[ r"\$;\b", TODO+r"\1#" ], # Subscript separator for array emulation.
[ r"\$!\b", TODO+r"\1#" ], # In numeric context, current value of errno
[ r"\$@\b", TODO+r"\1#" ], # Error message from last eval, do-FILE, or require
]
###########################################################################
# POD to Markdown
#
podChanges = [
[ r"^=head1 (.*)", r"#\1#" ],
[ r"^=head2 (.*)", r"##\1##" ],
[ r"^=head3 (.*)", r"###\1###" ],
[ r"^=head4 (.*)", r"####\1####" ],
[ r"^=head5 (.*)", r"#####\1#####" ],
[ r"^=head6 (.*)", r"######\1######" ],
# [ pod, cut, over, back, item ' -- SPECIAL
# Skipping the repeatable I<<<<<...>>>>> cases.
[ r"\bB<([^>]+)>", r"`\1`" ],
[ r"\bC<([^>]+)>", r"`\1`" ],
[ r"\bF<([^>]+)>", r"_\1_" ],
[ r"\bI<([^>]+)>", r"''\1''" ],
[ r"\bL<([^>]+)>", r"[\1]" ],
# E<sol> lt gt verbar html names decimal 127 0177 0x7F...
# Leaving over and back so we can still see the nesting.
]
def compileRegexes() -> None:
for i, c in enumerate(changes):
if (args.trace):
info("change %3d: s/%s/%s/" % (i, c[0], [c[1]]))
if (len(c) != 2):
raise ValueError("changes %3d is len %d, not 2." % (i, len(c)))
try:
c.append(re.compile(c[0]))
except re.error:
fatal("## Can't compile regex #%d: LHS: /%s/" % (i, c[0]))
for i, c in enumerate(specialVarChanges):
try:
if (args.trace):
info("specialVarChanges %3d: s/%s/%s/" % (i, c[0], [c[1]]))
if (len(c) != 2):
raise ValueError("specialVarChanges %3d is len %d, not 2." % (i, len(c)))
re.compile(c[0])
except re.error:
fatal("Can't compile specialVarChanges regex #%d: LHS: /%s/" % (i, c[0]))
for i, c in enumerate(podChanges):
try:
if (args.trace):
info("podChanges %3d: s/%s/%s/" % (i, c[0], [c[1]]))
if (len(c) != 2):
raise ValueError("podChange %3d is len %d, not 2." % (i, len(c)))
re.compile(c[0])
except re.error:
fatal("Can't compile podChanges regex #%d: LHS: /%s/" % (i, c[0]))
###############################################################################
#
def varsInString(s:str) -> str:
"""Expand variable references inside a Perl double-quoted string
(may come in with ';' and/or comment at end)
(perhaps should also drop a final "\\n"?)
"""
if (args.oldVarsInString): return varsInString1(s)
else: return varsInString2(s)
def varsInString1(s:str) -> str:
# Strip comment if any (imperfect))
s = s.rstrip(" ;")
com = ""
mat = re.search(r"\s*#[^'\"]*$", s)
if (mat):
com = s[mat.start():]
s = s[0:mat.start()]
re.sub(r'"(.*?(?<!\\))"', varSubFunc, s)
s = re.sub(r'\\n"$', "\"", s)
return s+com
def varSubFunc(mat):
"""Split the string at each $x{}, $x[], or $x, and make it a concat
instead. Could instead switch to .format(), but it doesn't seem any easier.
"""
x = mat.group(1)
x = re.sub(r"\$(\w+)\{(.*?)\}", r'" + str(\1[\2]) + "', x)
x = re.sub(r"\$(\w+)\[(.*?)\]", r'" + str(\1[\2]) + "', x)
x = re.sub(r"\$(\w+)", r'" + str(\1) + "' , x)
return x
###############################################################################
#
def varsInString2(s:str) -> str:
"""Extract variables from inside quotes, and handle Perl's many quote types.
==> Move to top level so only unquoted stuff goes to the regexes. Requires
separately collecting stuff outside of quotes, and passing that through
with some substitutes for the quotes bits inserted then replaced.
(see http://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators)
Customary Generic Meaning Interpolates
--------- ------- ------- ------------
'' q{} Literal no
"" qq{} Literal yes
`` qx{} Command yes*
qw{} Word list no
// m{} Pattern match yes*
qr{} Pattern yes*
s{}{} Substitution yes*
tr{}{} Transliteration no (but see below)