How can I make conditional replacements in Perl?

I am trying to convert the following:

bool foo(int a, unsigned short b)
{
    return pImpl->foo(int a, unsigned short b);
}

in

bool foo(int a, unsigned short b)
{
    return pImpl->foo(a, b);
}

In other words, I need to remove the type definition in strings that are not a function definition.

I am using Linux.

The following removes the type in both lines:

perl -p -e 's/(?<=[,(])\s*?(\w+ )*.*?(\w*)(?=[,)])/ $2/g;' fileName.cpp

How to replace only the line starting with 'return' and still make several changes on the same line?

+5
source share
2 answers

Add a statement if:

perl -p -e 's/regex/replacement/g if /^\s*return/;' fileName.cpp

Alternatively, you can use the line you pass perl -p to be the body of the loop:

perl -p -e 'next unless /^\s*return/; s/add/replacement/g;' filename.cpp
+8
source

- → , . script, a → , .

0

All Articles