views:

810

answers:

4

I don't have a lot of experience will Perl, but I believe what I am doing should be working.

First, from the Windows command prompt I generate a text file of all the files in a directory:

dir c:\logfiles /B > config.txt

Output:

0001_832ec657.log
0002_a7c8eafc.log

I need to feed the "config.txt" file to another executable, but before I do so I need to modify the file to add some additional information that the executable needs. So I use the following command:

perl -p -i.bak -e 's/log/log,XYZ/g' config.txt

I'm expecting the result to be:

0001_832ec657.log,XYZ
0002_a7c8eafc.log,XYZ

However, the "config.txt" file is not modified. Using the "-w" option I get the warning message:

Useless use of a constant in void context at -e line 1.

What am I doing wrong? Thanks.

A: 

The Perl script works from a linux shell, maybe you aren't escaping something correctly.

Mitch
A: 

If you are in Windows, there may be a shell issue that I'm not seeing, but a variant of what you're doing works as expected for me:

perl -i.bak -ple 's/log/log,XYZ/' config.txt

Unless you have repeated substitutions on the same line, you shouldn't need the /g modifier. As with Mitch, I'm on Linux though, so that may be it.

Telemachus
+18  A: 

Windows cmd.exe does not use ' as string delimiters, only ". What you're doing is equivalent to:

perl -p -i.bak -e "'s/log/log,XYZ/g'" config.txt

so -w is complaining "you gave me a string but it does nothing".

The solution is to use double quotes instead:

perl -p -i.bak -e "s/log/log,XYZ/g" config.txt

or to simply leave them off, since there's no metacharacters in this command that would be interpreted by cmd.exe.

Addendum

cmd.exe is just a really troublesome beast, for anybody accustomed to sh-like shells. Here's a few other common failures and workarounds regarding perl invocation.

@REM doesn't work:
perl -e"print"
@REM works:
perl -e "print"
@REM doesn't work:
perl -e "print \"Hello, world!\n\""
@REM works:
perl -e "print qq(Hello, world!\n)"
ephemient
I had a feeling it was going to be obvious. Thanks!
gatorfax
A: 
Chas. Owens
Yeah, or just use double quotes. What if this code has to run on other machines? There is nothing he which would require replacing cmd.
Ed Swangren
One liners are not meant to be portable code. And how likely is it that Perl will be installed on another Windows machine? Also, if you are a Windows person it is probably a good idea to get used to PowerShell since it is part of 2008 Server.
Chas. Owens
Cmd.exe sucks badly, if it gets in your way enough a shell change is worth considering. Another shell is worth considering. MSYS and MinGW provide a lighter weight way to get your unix environment than Cygwin. They, too, are worth looking into. http://www.mingw.org/
daotoad