Goku Goku - 4 months ago 7
Perl Question

Perl one liner is not working inside perl script

I'm trying to remove the string @my.mail.com from the file - list.txt, using the one liner from my perl script.
(Perl script is kicked off from windows server)

r12355 test@my.mail.com
r29555 test@my.mail.com
r29555 trial@my.mail.com
@my.mail.com
r295721 xxx@my.mail.com
r295722 yyyy@my.mail.com
@my.mail.com
r295140 test@my.mail.com
r295145 test@my.mail.com
@my.mail.com


Below are the options I have tried while calling inside the perl script:

`perl -pi.bak -e 's/\s+\@my\.mail\.com\s+//g;' D:\\myfolder\\list.txt`;

system("perl -pi.bak -e 's/\s+\@my\.mail\.com\s+//g;' D:\\myfolder\\list.txt");

system( q( perl -l -pi.bak -e 's/\s+\@my\.mail\.com\s+//g;' D:\\myfolder\\list.txt ) );


I'm expecting result like

r12355 test@my.mail.com
r29555 test@my.mail.com
r29555 trial@my.mail.com
r295721 xxx@my.mail.com
r295722 yyyy@my.mail.com
r295140 test@my.mail.com
r295145 test@my.mail.com


Not sure If I'm missing something silly , any inputs are really appreciated. Thanks in advance!

Answer

There are two problems here. Firstly you have escaped the backslashes in the file path but not in the regex pattern, and secondly you have used single quotes around the parameter to the -e option, which Windows doesn't recognise as delimiters

This variation should work for you. It uses single quotes (actually q{...}) to protect the backslashes so that nothing needs to be escaped

system q{perl -pi.bak -e "s/\s+\@my\.mail\.com\s+//g" D:\myfolder\list.txt};

However it is poor practice to shell out to another perl process from within your Perl program. It can be done directly in your main code by adding this, which is much more readable and less easy to get wrong

{
    local @ARGV = 'D:\myfolder\list.txt';
    local $^I = '.bak';

    while ( <> ) {
        s/\s+\@my\.mail\.com\s+//g;
        print;
    }
}
Comments