quinekxi
quinekxi

Reputation: 889

How can I parse ini file using Perl regex or in anyways?

I have this ini file.

day=Mon
time=01:00:00
occurence=weekly
taskname=monitorschedule
taskrun=C:\monitor.bat

I want to have an output like this for create a new schedule job in a windows xp.

schtasks.exe /create /tr c:\monitor.bat /sc weekly /d Mon /st 01:00:00 /tn monitorschedule /ru "system"

I have tried something like this:

my $file = 'C:\strawberry\perltest\ini file\MonitorSchedule.ini';
my $d;
my $t;
my $o;
  my $n;
    my $r;
    my $u = '"system"';

    open (TEST, "<", $file) or die $!; # open ini file
    while(<TEST>) # read all lines of the ini file
    {
    if($_ =~ m/day/)
    {
    my $day = $_;
    my @days = split('=', $day);
    $d = $days[1];
    }
    if($_ =~ m/time/)
    {
    my $time = $_;
    my @times = split('=', $time);
    $t = $times[1];
    }
    if($_ =~ m/occurence/)
    {
    my $occurrence = $_;
    my @occurrences = split('=', $occurrence);
    $o = $occurrences[1];
    }
    if($_ =~ m/taskname/)
    {
    my $taskname = $_;
    my @tasknames = split('=', $taskname);
    $n = $tasknames[1];
    }
    if($_ =~ m/taskrun/)
    {
    my $taskrun = $_;
    my @taskruns = split('=', $taskrun);
    $r = $taskruns[1];
        }
    }
    close TEST;

print "schtasks.exe /create /tr $r /sc $o /d $d /st $t /tn $n /ru $u";

Unfortunately the output is not what I want.

schtasks.exe /create /tr C:\monitor.bat /ru "system".

I don't know what's wrong. Where am I wrong?

Upvotes: 0

Views: 856

Answers (3)

johnsyweb
johnsyweb

Reputation: 141850

Why re-invent the wheel? There is a perfectly acceptable INI file reader in CPAN.

> cat monsch.pl 
#!/usr/bin/env perl -w

use strict;
use Config::INI::Reader;

my $filename = "/path/to/MonitorSchedule.ini";

my $ini = Config::INI::Reader->read_file($filename);
my $global_section = $ini->{'_'};

printf "schtasks.exe /create /tr %s /sc %s /d %s /st %s /tn %s /ru \"system\"\n"
    , $global_section->{'taskrun'}
    , $global_section->{'occurence'}
    , $global_section->{'day'}
    , $global_section->{'time'}
    , $global_section->{'taskname'}
    ;
> ./monsch.pl 
schtasks.exe /create /tr C:\monitor.bat /sc weekly /d Mon /st 01:00:00 /tn monitorschedule /ru "system"

Upvotes: 8

勿绮语
勿绮语

Reputation: 9320

To make the code cleaner, just have a "translation" hash:

use strict;
use warnings;

my $translation = {
    "day" => "d",
    "time" => "st",
    "taskname" => "tn",
    "taskrun" => "tr",
    "occurence" => "sc"
};

my $command = "schtasks.exe /create ";
while (<DATA>) {
    chomp $_; 
    my ($key, $value) = split(/=/); 
    $command .= "/$translation->{$key} $value ";
}
$command .= "/ru \"system\"";

__DATA__
day=Mon
time=01:00:00
occurence=weekly
taskname=monitorschedule
taskrun=C:\monitor.bat

Upvotes: 4

SAN
SAN

Reputation: 2247

Use Config::IniFiles or Config::INI::Reader as suggested in How can I access INI files from Perl?

Upvotes: 3

Related Questions