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, '&lt;', $filename or die "Can't open $filename: $!";

    while (my $line = &lt;$fh&gt;) {

        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 =~ /\\$/) {
                $print_ended = 1;    
                $concat_print .= $line . "\n";     
            }
            else {
                (my $newline = $line) =~ s/print /print(/;
                print $newline . ")\n";
            }
        }
        else {
            print $line . "\n";            
        }
    }
}
\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 = &lt;&gt;) {
    $line =~ s/print \s+ (.+? (?: [^\\]\h*$ ) )/print($1)/xgsm;
    print $line;
}