Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: update values in one file from another

by secret (Beadle)
on Dec 07, 2005 at 10:00 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://514771]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-04-25 08:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found