First, thank you for providing clear examples. It makes debugging profoundly easier.
To understand what strict is, see Use strict warnings and diagnostics or die. Several of the bugs in this code would have been immediately apparent if you used this tool.
$envfile="/root/env.properties";
@envFile=<$env>;
open my $env, '<', $envfile or die "Can't read old file: $!";
You're trying to read in your file before you've opened your file handle. Therefore the array is empty, and you never execute anything in your foreach loop.
open my $in, '<', $file or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";
You never initialize the value for
$file. I'm very surprised you aren't dying right here.
print "\nFile contents:";
print @envFile;
foreach $envline (@envFile){
while ( <$in> ){
Not indenting this line makes following flow challenging.
print "$. $_";
if($envline =~/$DOMAIN_DB_CONN_STR=.*:1521:.*/ && $_=~/$DOMAIN
+_DB_CONN_STR=.*:1521:.*/){
You never initialize
$DOMAIN_DB_CONN_STR, so the regular expression will actually check
/=.*:1521:.*/, which is presumably not what you want.
print "\nMatch";
$line=$_;
$line =~ s/$DOMAIN_DB_CONN_STR=.*:1521:.*/NUANCE_DB_CO
+NN_STR=$dbhost:$dbport:$dbschema/;
Same thing for
$dbhost,
$dbport, and
$dbschema.
print $out $line;
}
}
}
You appear to intend to check every line against every other line, but this would only execute for the first line of the
$env file because you don't reset/rewind the
$in file. You could either rewind (
seek) or pull the
$in file into an array as well.
Following the extra input you gave in Re^2: read the value of variable from environment file and set it to another properties file using perl script and rewriting this in an inefficient but easy-to-follow manner, you might have:
use strict;
use warnings;
my $envfile = "/root/env.properties";
my $file = 'input.txt'; # Or whatever
open my $env, '<', $envfile or die "Can't read old file: $!";
open my $in, '<', $file or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";
my @envFile = <$env>;
my @inFile = <$in>;
print "\nFile contents:";
print @envFile;
my $dbhost = '';
my $dbport = '';
my $dbschema = '';
foreach my $envline (@envFile){
my $inLineCount = 0;
foreach my $inline (@inFile){
$inLineCount++;
print "$inLineCount $inline";
foreach my $DOMAIN_DB_CONN_STR ('FINANCE_DB_CONN_STR', 'MARKET
+ING_DB_CONN_STR') {
if($envline =~/$DOMAIN_DB_CONN_STR=.*:1521:.*/ && $inline
+=~/$DOMAIN_DB_CONN_STR=.*:1521:.*/){
print "\nMatch";
my $line = $inline;
$line =~ s/$DOMAIN_DB_CONN_STR=.*:1521:.*/NUANCE_DB_CO
+NN_STR=$dbhost:$dbport:$dbschema/;
print $out $line;
}
}
}
}
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.