Question

I want to read some parameters from a file using perl script. I used grep command to find the values of thoses parameters.

#!/usr/bin/perl

if( scalar @ARGV ==0)
{
  die "Number of argument is zero. Please use: perl <script_name> <cdc68.ini> \n";
}


if( !-f $ARGV[0])     ## if the 1st arg is not a file
{
   die "$ARGV[0] is not a valid file type \nInput Arguments not correct!!! \n";
}

my $file_cnf=$ARGV[0];

my $DEST_PATH=`grep relogin_logs $file_cnf | cut -d "=" -f2`;

my $SRC_PATH=`grep dump_logs $file_cnf | cut -d "=" -f2`;
my $FINAL_LOG=`grep final_log $file_cnf | cut -d "=" -f2`;

print "\n$DEST_PATH \n $SRC_PATH \n $FINAL_LOG\n";


if ( !-d $DEST_PATH)
{
  die "$DEST_PATH is not a dir";
}

else
{
  print "ok";
}

the file I want to read is

cat cdc68.ini
reconn_interval=15
relogin_logs=/osp/local/home/linus/pravej/perlD/temp/relogin/
dump_logs=/osp/local/home/linus/pravej/perlD/temp/
final_log=/osp/local/home/linus/pravej/perlD/final_log/
Number_days=11

Sample output:

perl readconfig.pl cdc68.ini
/osp/local/home/linus/pravej/perlD/temp/relogin/
/osp/local/home/linus/pravej/perlD/temp/
/osp/local/home/linus/pravej/perlD/temp/relogin/
is not a dir at readconfig.pl line 26.

Can anyone suggest what I'm doing wrong here? Please note that I dont want to use any perl module like config or tiny.pm. Also these dir already exist in my unix system Thanks in advance for your help

Was it helpful?

Solution 2

mpapec's alternative parsing is much better than your current script. But, for what it's worth, your original problem is that the result of the backtick operator includes the newline character at the end of the string.

You can remove it with chomp, eg:

my $DEST_PATH=`grep relogin_logs $file_cnf | cut -d "=" -f2`;
chomp $DESTDIR;

Do this with the result of all your backtick commands.

OTHER TIPS

You can use perl parsing instead of shell utils

my $file_cnf = $ARGV[0];

open my $fh, "<", $file_cnf or die $!;
my %ini = map /(.+?)=(.+)/, <$fh>;
close $fh;

print "\n$ini{relogin_logs} \n $ini{dump_logs} \n $ini{final_log}\n";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top