Can anyone tell me from looking at the code below why I'm only able to have one value per key in the hash despite using a hash of arrys. Below is my code. Any suggestions are appreciated. It seems from what I can tell that the code doesn't enter the part
when it encounters a key that exists but doesn't have the particular value being examined stored in it. Once one value is stored in that slot of the key then all subsequent values that happen to fall under that key are caught by the code
which won't add the key then of course. But this should not be happening since the value in question (i.e. $2) has not been added yet. Only the key is present with another value currently being sotred there. Thanks for your help.
Code:
elsif (exists $hash{$2})
{
print "We're adding a second value. Examining with $line1\n";
push @{ $hash{$2} }, $3;
}
Code:
if (exists $hash{$2}[$3] )
{
print "key value pair already exists for elemetn $line1\n";
#do nothing
}
Code:
#use strict;
#print "$ARGV[0]";
open(MY_FILE1,$ARGV[0]);
open(OUTPUT, ">>output.txt");
while(<MY_FILE1>)
{
chomp;
my $line1 = $_;
my %hash = ();
my $flag = 0;
my $view = 0;
my $noCAASsource = 0;
open(MY_FILE2,$ARGV[1]);
while(<MY_FILE2>)
{
chomp;
my $line2 = $_;
if($line2 =~ /^\s*$/)
{
#do nothing
}
elsif($line2 =~ /^($line1)\s+/)
{
if($line2 =~ /^($line1)\s+CAAS.+\.([^.]+)\.([^.]+)/ )
{
$flag = 1;
if (exists $hash{$2}[$3] )
{
print "key value pair already exists for elemetn $line1\n";
#do nothing
}
elsif (exists $hash{$2})
{
print "We're adding a second value. Examining with $line1\n";
push @{ $hash{$2} }, $3;
}
else
{
print "We're adding a brand new key\n";
$hash{$2} = $3;
}
}
if($line2 =~/^($line1)\s+View/)
{
$view = 1;
}
if($line2 =~/^($line1)\s+NO CAAS Source/)
{
$noCAASsource = 1;
}
}
}
if($flag == 0 && $view == 0 && $noCAASsource == 0)
{
print "nothing found\n";
print OUTPUT "nothing found\n";
}
elsif($flag == 0 && $view == 1)
{
print "view\n";
}
elsif($flag == 0 && $view == 0 && $noCAASsource == 1)
{
print "NO CAAS Source\n"
}
elsif($flag == 1 && $view == 0)
{
print keys %hash, ;
print "\n";
}
elsif($flag == 1 && $view == 1)
{
foreach (keys %hash)
{
#remove all whitespace using search and replace
$_ =~ s/ //g;
chomp;
print OUTPUT "$_,";
}
print OUTPUT "\t";
foreach (keys %hash)
{
my $key = $_;
foreach (0 .. @{ $hash{$key} } - 1)
{
my $n = $hash{$key}[$_];
$n =~ s/ //g;
print OUTPUT $n . ", ";
}
}
print OUTPUT "\n";
print "View $line1 has a segment and COBOL field\n";
}
$noCAASsource = 0;
$flag = 0;
$view = 0;
close MY_FILE2;
}
close OUTPUT;
close MY_FILE1;
close MY_FILE2;