Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: update values in one file from another

by secret (Beadle)
on Dec 07, 2005 at 10:00 UTC ( #514771=note: print w/replies, xml ) Need Help??


in reply to update values in one file from another

A simple approach :

use strict ; use warnings ; my %initial = () ; my %seen = () ; # increment if animal is seen my $new_value ; # Load initial values open FILE, '<', 'file1.txt' or die 'Failed to open file1' ; while ( my $line = <FILE> ) { my ($animal, $count ) = split " ", $line ; $initial{$animal}=$count ; } close FILE ; # Open file to look for new animals open UPDATE , '<', 'file2.txt' or die 'Failed to open file2' ; while ( my $line = <UPDATE> ) { # We assume a special pattern form your example file my $animal = $1 if $line =~ m/^(\w+) feed/ ; $seen{$animal}++ ; } close UPDATE ; # Open result file for writing open FILE, '>','file1.txt' or die 'Failed to open file1 for writing'; foreach ( sort keys %initial) { #Deal with the three possible case : #new animal, previously existing but unseen, or existing and seen if ( defined $seen{$_} and not defined $initial{$_} ) { $new_value = 1 } elsif ( not defined $seen{$_} and defined $initial{$_} ) { $new_value = $initial{$_} } else { $new_value = $initial{$_} + 1 } print FILE "$_ $new_value\n" ; } close FILE ;

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2020-02-19 11:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What numbers are you going to focus on primarily in 2020?










    Results (81 votes). Check out past polls.

    Notices?