Re: Hash problem



Andrej Kastrin wrote:
> Dear all,

Hello,

> I have bar separated file:
> name1|345
> name2|201
> ...
>
> I store it into a hash;
> while (<FILE_A>) {
> chomp;
> ($name,$score) = split (/\|/,$_);
> $hash{$name} = $score;
> }
>
> Then I have second file:
> ID - 001
> NA - name1
> NA - name2
>
> ID - 002
> NA - name2
> NA - name4
> ...
>
> I match all ID's and NA's:
>
> while (<FILE_B>) {
> chomp;
> if (/^ID/ {
> $ID = substr($_,5);
> }
> elseif (/^NA/) {
> $NA = substr($_,5)
> }
>
> Now I have to do somethig like;
> 001 | 345+201
> ...
>
> So, I want to read ID and NA fields from second file and then with each
> ID print the sum of scores from first file.
>
> Any suggestion. Which structure should I use to do that. Thank's in
> advance.

It looks like you could do something like this (UNTESTED):

my %scores;
while ( <FILE_A> ) {
chomp;
my ( $name, $score ) = split /\|/;
$scores{ $name } = $score;
}

my ( $ID, %ids );
while ( <FILE_B> ) {
if ( /^ID\s*-\s*(.+)/ ) {
$ID = $1;
}
elseif ( /^NA\s*-\s*(.+)/ ) {
$ids{ $ID } += $scores{ $1 };
}
}

for my $id ( keys %ids ) {
print "$id | $ids{$id}\n";
}



John
--
use Perl;
program
fulfillment
.



Relevant Pages

  • Hash problem
    ... NA - name2 ... NA - name4 .... ... chomp; if (/^ID/ { ... I want to read ID and NA fields from second file and then with each ID print the sum of scores from first file. ...
    (perl.beginners)
  • Re: Hash problem
    ... Let's assume the resulting hash is %scores. ... > NA - name2 ... I want to read ID and NA fields from second file and then with each ...
    (perl.beginners)
  • Re: Hash problem
    ... NA - name2 ... NA - name4 ... ... chomp; if (/^ID/ { ... I want to read ID and NA fields from second file and then with each ...
    (perl.beginners)
  • Re: Perl code for comparing two files
    ... Hash: SHA1 ... chomp $line; ... or die "could not open $second_file: ... foreach my $key (sort keys ...
    (perl.beginners)
  • Re: purging rows from fileA.txt based on fileB.txt
    ... read A line by line and check for existence in the hash. ... Also I am not sure how the memory would handle 13million lines of about ... chomp $banWord; ... we will also need some sample input from both input files if we are to ...
    (perl.beginners)