4
\$\begingroup\$

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 =~ /\\$/) {
                $print_ended = 1;    
                $concat_print .= $line . "\n";     
            }
            else {
                (my $newline = $line) =~ s/print /print(/;
                print $newline . ")\n";
            }
        }
        else {
            print $line . "\n";            
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ You've made great progress! Glad to see feedback applied. :) \$\endgroup\$ – simbabque Nov 21 '17 at 14:02
  • \$\begingroup\$ Could you add an example input file please? \$\endgroup\$ – simbabque Nov 21 '17 at 14:03
  • 1
    \$\begingroup\$ codereview.stackexchange.com/questions/155547/… What I used as an example. \$\endgroup\$ – Ludisposed Nov 21 '17 at 14:10
  • 3
    \$\begingroup\$ Do you know about the program 2to3 that ships with python3? \$\endgroup\$ – Austin Hastings Nov 21 '17 at 14:12
  • 1
    \$\begingroup\$ @AustinHastings Nope, I did not. :) However the intention was to learn perl anyway, so no time was wasted. \$\endgroup\$ – Ludisposed Nov 21 '17 at 14:13
3
\$\begingroup\$

\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;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.