# a Python2 to Python3 print fixer in perl

Sometimes, I'm reviewing old questions written in Python2, with no parenthesis around print statements. Or I'm changing one of my older codes, also without parenthesis around print statements.

It annoys me to do this manually, so I decided to write a little perl script to change it for me, however it looks rather ugly. And I think I'm missing some obvious regex to do this?

I don't yet write to another file, but just print to the commandline.

Note that I'm making the assumption that lines that print and are net yet ended, end with \

use strict;
use warnings;

my @filenames = @ARGV;

foreach my $filename (@filenames){ my$print_ended = 0;
my $concat_print = qw{}; open my$fh, '<', $filename or die "Can't open$filename: $!"; while (my$line = <$fh>) { chomp$line;
if ($print_ended) {$concat_print .= $line;$print_ended = $line =~ /\$/; if (! print_ended) { (my newline = concat_print) =~ s/print /print(/; print newline . ")\n"; concat_print = qw{}; } } elsif (line =~ /print /) { if (line =~ /$$/extract_itex]/) { print_ended = 1; concat_print .= line . "\n"; } else { (my newline = line) =~ s/print /print(/; print newline . ")\n"; } } else { print line . "\n"; } } }  • You've made great progress! Glad to see feedback applied. :) – simbabque Nov 21 '17 at 14:02 • Could you add an example input file please? – simbabque Nov 21 '17 at 14:03 • codereview.stackexchange.com/questions/155547/… What I used as an example. – Ludisposed Nov 21 '17 at 14:10 • Do you know about the program 2to3 that ships with python3? – Austin Hastings Nov 21 '17 at 14:12 • @AustinHastings Nope, I did not. :) However the intention was to learn perl anyway, so no time was wasted. – Ludisposed Nov 21 '17 at 14:13 ## 1 Answer \h matches horizontal white spaces /x modifier instructs regex to ignore white spaces (readability) /m modifier instructs ^  anchors to match begin/end of line, instead of string! local /; # read all text at once while (my line = <>) { line =~ s/print \s+ (.+? (?: [^\$$\h*$ ) )/print($1)/xgsm; print$line;
}