简体   繁体   中英

How to update path in Perl script in multiple files

I am working on creating some training material where I am using perl. One of the things I want to do is have the scripts be set up for the student correctly, regardless of where they extra the compressed files. I am working on a Windows batch file that will copy the perl templates to the working location and then update path in the copy of the perl template files to the correct location. The perl template have this as the first line:

#!_BASE_software/perl/bin/perl.exe

The batch file looks like this:

SET TRAINING=%~dp0
copy %TRAINING%\template\*.pl %TRAINING%work
%TRAINING%software\perl\bin\perl -pi.bak -e 's/_BASE_/%TRAINING%/g' %TRAINING%work\*.pl

I have a few problems with this:

  1. Perl doesn't seem to like the wildcard in the filename
  2. It turns out that %TRAINING% is going to expand into a string with backslashes which need to be converted into forwardslashes and needs to be escaped within the regex.

How do I fix this?

First of all, Windows doesn't use the shebang line, so I'm not sure why you're doing any of this work in the first place.

Perl will read the shebang line and look for options if perl is found in the path, even on Windows, but that means that #!perl is sufficient if you want to pass options via the shebang line (eg #!perl -n ).

Now, it's possible that you use Cygwin, MSYS or some other unix emulation instead of Windows to run the program, but you are placing a Windows path in the shebang line ( C:... ) rather than a unix path, so that doesn't make sense either.

There are three additional problems with the attempt:

  1. cmd uses double-quotes for quoting.
  2. cmd doesn't perform wildcard expansion like sh , so it's up to your program do it.
  3. You are trying to generate Perl code from cmd . ouch.

If we go ahead, we get:

"%TRAINING%software\perl\bin\perl" -MFile::DosGlob=glob -pe"BEGIN { @ARGV = map glob, @ARGV; $base = $ENV{TRAINING} =~ s{\\}{/}rg } s/_BASE_/$base/g" -i.bak -- %TRAINING%work\*.pl

If we add line breaks for readability, we get the following (that cmd won't accept):

"%TRAINING%software\perl\bin\perl"
   -MFile::DosGlob=glob
   -pe"
      BEGIN {
         @ARGV = map glob, @ARGV;
         $base = $ENV{TRAINING} =~ s{\\}{/}rg
      }
      s/_BASE_/$base/g
   "
   -i.bak -- %TRAINING%work\*.pl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM