Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Merging two list with simple operation

by ahmad (Hermit)
on Jul 31, 2010 at 18:48 UTC ( [id://852267]=note: print w/replies, xml ) Need Help??


in reply to Merging two list with simple operation

Try this:

#!/usr/bin/perl use strict; use warnings; my %HASH; open(F1,"file1"); while (<F1>) { chomp; my ($k,$v) = split /\s+/,$_,2; $HASH{$k} = $v; } close(F1); open(F2,"file2"); while (<F2>) { chomp; my ($k,$v) = split /\s+/,$_,2; if (exists $HASH{$k} ) { $HASH{$k} *= $v; }else{ $HASH{$k} = $v; } } close(F2); # write output to file open(OUT,">newfile"); while (my ($k,$v) = each %HASH) { print OUT "$k $v\n"; } close(OUT);

Replies are listed 'Best First'.
Re^2: Merging two list with simple operation
by fanticla (Scribe) on Jul 31, 2010 at 19:08 UTC

    @ahmad: THANK YOU VERY MUCH. It works great!!! 1000 better as my original script!

Re^2: Merging two list with simple operation
by rir (Vicar) on Aug 04, 2010 at 21:01 UTC
    I'll endorse ahmad's solution. I'd just point out that the magical quality of @ARGV can be handy for this kind of data munging and that chomp %hash chomps the hash's values.

    Be well,
    rir

    #!/usr/bin/perl use strict; use warnings; @ARGV = qw/ file1 file2/; my %h; while ( <> ) { /(\S+)\s+(\S+)/; $h{$1} = $h{$1} ? $h{$1}*$2 : $2; } print "$_ $h{$_}\n" for sort { $h{$a} <=> $h{$b} } keys %h;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://852267]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-04-26 00:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found