Hi fellow monks, I have a question, and I am a newbie. I was wondering, what is the best way to change this code so that if you do not find the matching key from the first file in the second file do not bother to leave it present in the ongoing iteration, so that when I print the end result out only the matching keys found in the first file that are also in the second file are joined and printed to the endfile. Is this a kind of a null output situation? Thanks.
#!/usr/bin/perl use strict; use warnings; my %file1; my $key; my $value; #usage() unless @ARGV == 0; my $inf1="file2"; open (IN1, "$inf1"); my $output_file = pop @ARGV; # read first file while (<IN1>) { chomp; ($key,$value) = split /:/, $_, 2 or warn "Bad data on line $. in file $ARGV, "; $file1{$key} = $value or warn "Bad data on line $. in file $ARGV, "; } continue { # reset line numbers for warning messages # end loop if ( eof ) # note special form of eof { close IN1; last; } } my $inf2="file3"; open (IN2, "$inf2"); my $outf1=">endfile"; open (OUT1,"$outf1"); # read second file while (<IN2>) { chomp; ($key,$value) = split /:/, $_, 2 or warn "Bad data on line $. in file $ARGV, "; if ( exists( $file1{$key} ) ) { $file1{$key} .= ''. $value or warn "Bad data on line $. in file $ARGV, "; } else { warn "Can\'t find key matching <$key> (line $.) " . "in file <$ARGV>, "; $file1{$key} = $value or warn "Bad data on line $. in file $ARGV, "; } } continue { last if ( eof ) # note special form of eof } #open( OUT, ">", $output_file ) #or die "Error opening $output_file for writing, "; foreach my $k ( sort keys %file1 ) { print OUT1 "$k:$file1{$k}\n"; } close (OUT1);
Edit, BazB: added readmore tag.
In reply to null output on hashes by tux242
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |