abbi
abbi

Reputation: 13

perl + create loop to print values from INI file

My name is abbi

My first perl script run on linux machine

This script read the INI file called (input) and print the values of val , param , name .....

How to create loop that print values of val1-valn OR loop to print values of param1-paramn... etc? (in place the print command's in the script )

n - Is the last number of each param

 #!/usr/bin/perl




 open(IN,"input") or die "Couldn't open input: $!\n"; 
 while(<IN>) { 
 chomp; 
 /^([^=]+)=(.*)$/; 
 $config{$1} = $2; 

 } 
 close(IN);


 print $config{val1};
 print $config{val2};
 print $config{val3};

 print $config{param1};
 print $config{param2};
 print $config{param3}; 

 print $config{name1};
 .
 .
 .
 .

example of the ini file from linux machine

cat input

  val1=1
  val2=2
  val3=3
  param1=a
  param2=b
  param3=c
  name1=abbi
  name2=diana
  name3=elena

Upvotes: 1

Views: 644

Answers (3)

sebthebert
sebthebert

Reputation: 12507

You can use Config::Tiny to read your .ini file. Then you can use the returned hash to filter what you want.

Upvotes: 2

Toto
Toto

Reputation: 91488

According to your last comment, this will do what you want:

use strict;
use warnings;

my %config;
my $max_n = 0;
my $input = 'input';
open my $in, '<', $input
    or die "unable to open '$input' for reading: $!";
while (<$in>) {
    chomp;
    if (/^(.*?(\d+))\s*=(.*)$/) { 
        $config{$1} = $3; 
        $max_n = $2 if $2 > $max_n;
    }
}
close $in or die "unable to close '$input': $!";

for my $n(1..$max_n) {
    for my $param (qw/val param/) {
        print "$param.$n = $config{$param.$n}\n" if exists $config{$param.$n};
    }
}

Upvotes: 1

user181548
user181548

Reputation:

How about this:

use warnings;
use strict;
my %config;

open my $input, "<", "input"
    or die "Couldn't open input: $!\n"; 
while(<$input>) { 
    chomp; 
    if ( /^([^=]+)=(.*)$/) { 
        $config{$1} = $2; 
    }
} 
close($input) or die $!;

for (sort keys %config) {
    if (/param\d+/) {
        print "$config{$_}\n";
    }
}

Upvotes: 0

Related Questions