2

I have create a simple perl script to use Regex and extract a value from the text file. I have used windows to develop this script and it is working fine in windows

use strict;
use warnings;
use File::Slurp;

my $content = read_file("config.ini");

my $lin_targetdir = $1 if $content =~ m/targetDirectory\s*=\s*(.*)/;

print($lin_targetdir); # /opt/mypath  in linux i am getting this output

and my config is

[prdConfig]
IP = xxxxxx
UserID = yyyyyy
password = "zzzzzzz"
targetDirectory = /opt/mypath

however when i run the above in Linux (centos 7) the script is not printing the value. What went wrong in my code ? Can you please help me ?

backtrack
  • 7,996
  • 5
  • 52
  • 99
  • It works fine on my Debian 11 (Perl v5.32.1) and Windows 10 (Strawberry Perl v5.30). – Dada Aug 07 '21 at 12:21
  • what is the expected output, what do you want? what did you get? – iuridiniz Aug 07 '21 at 12:32
  • 4
    On linux you may be running it against a config file with DOS line endings (\r\n) so the \r is being captured,and when printed out, moves the cursor back to the start of the line and wipes out what's just been printed. – Dave Mitchell Aug 07 '21 at 12:45
  • Hi @DaveMitchell, you saved me, you are correct. i just covered the config.ini with dos2unix and ran the above. it worked. great and thanks – backtrack Aug 07 '21 at 13:36
  • 1
    There are probably modules that are designed to read INI files that will work better than your homemade version. – TLP Aug 07 '21 at 16:06

1 Answers1

3

Exclude the carriage return with the regex itself:

/targetDirectory\s*=\s*(\V*)/

Reference:

As Perl 5.10 specified in the documentation, \V is the same as [^\n\cK\f\r\x85\x{2028}\x{2029}] and shouldn't match any of \n, \r or \f, as well as Ctrl+(Control char) (*nix), 0x85, 0x2028 and 0x2029.

Alternative:

/targetDirectory\s*=\s*([^\r\n]*)/

to exclude line feed and carriage return characters only.

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37