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开发者_如何学C 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 )
- the loop must have option to match the parameter for example print only param1 until paramn values
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
You can use Config::Tiny to read your .ini file. Then you can use the returned hash to filter what you want.
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};
}
}
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";
}
}
精彩评论