0

I have been struggling with perl syntax. I am trying to learn enough to do a large conditional replacement on the source code of another project but keep running into trouble. I wrote a simple script to test my problems and this and it worked fine. I tried it on a file and it no longer worked. The file contains the same text as my test string.

I imagine I have to do something special reading in the file but I do not have a clue as to what.

test.sh:

#!/usr/bin/perl
use strict;
use warnings;


my $matching = 'Logger\.getInstance\(\)\.addEntry\(((.|\n)*),((.|\n)*),((.|\n)*),((.|\n)*)\)';
my $replacement = '"Logger\.getInstance\(\).addEntry\($1,$7\)"';

my $test_str = "Logger\.getInstance\(\)\.addEntry\(\"error\", \"Thing2D\.PATH_TYPE\", new Object\(\) \{\}\.getClass\(\)\.getEnclosingMethod\(\)\.getName\(\), \"New PATH_TYPE was added and not filled in\.\");";


print "----\nstring:\n" . $test_str . "\n\nreplaced:\n\n";

$test_str =~ s/$matching/$replacement/ee;
print "\n\n" . $test_str . "\n\n\n";


die qq[Usage: perl $0 <subject_file>\n] unless @ARGV == 1;

open my $fh_subject, qq[<], shift @ARGV or die qq[Cannot open input file: $!\n];

my $subject_content;
{
    local $/ = undef;
        $subject_content = <$fh_subject>;
}

print "----\nString:\n" . $subject_content . "\n\nreplaced:\n\n";

$subject_content =~ "s/$matching/$replacement/ee";
print $subject_content;

test.txt:

Logger.getInstance().addEntry("error", "Thing2D.PATH_TYPE", new Object() {}.getClass().getEnclosingMethod().getName(), "New PATH_TYPE was added and not filled in.");

and the command line:

./test.sh test.txt

Thank you for helping out!

1 Answer 1

4
$subject_content =~ s/$matching/$replacement/ee;

instead of

$subject_content =~ "s/$matching/$replacement/ee";
Sign up to request clarification or add additional context in comments.

1 Comment

I knew it was something simple! Thank you very much. I'm trying to learn a bit of pearl for those repetitive tasks I do. This helps a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.