in reply to Re: update values in one file from another
in thread update values in one file from another

You can doi it like this:

use warnings; use strict; # Create a test file open outFile, ">", "file1.txt"; print outFile <<end; rabbit 1 hen 0 pig 2 cow 2 sheep 5 end close outFile; my %fed; $fed{$1}++ while <DATA> =~ m/^(\w+)\s/; local @ARGV = ('file1.txt'); local $^I = '.bak'; while (<>) { m/^(\w+)\s+(\d+)$/; printf "$1\t%d\n", exists $fed{$1} ? $2+1 : $2; } __DATA__ rabbit feed 10kg used on 21/10/2005 by consumer1 cow feed 100kg used on 11/11/2005 by consumer1 sheep feed 50kg used on 24/11/2005 by consumer3

file1.txt contains:

rabbit 2 hen 0 pig 2 cow 3 sheep 6

DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^3: update values in one file from another
by Hue-Bond (Priest) on Dec 07, 2005 at 11:06 UTC

    My error was:

    local $^I = '.bak'; while (<>) { m/^(\w+)\s+(\d+)$/; $2++; ## this

    I guess that would work if I used Tie::File or something like that. Thank you!

    --
    David Serrano

Re^3: update values in one file from another
by Anonymous Monk on Dec 08, 2005 at 09:50 UTC
    If I wanted to change the logic of the above code so all values not in $fed{1} were incremented by 1 instead , how would I do this ?
    I tried doing this
    local @ARGV = ('file1.txt'); local $^I = '.bak'; while (<>) { m/^(\w+)\s+(\d+)$/; printf "$1\t%d\n", not exists $fed{$1} ? $2+1 : 0; }
    This only works the first time it's run, after that everything that isn't in $fed{1} is always only set to 1.
    I was trying to get it to increment all other values by 1 each time and set the $fed{1} values to 0
Re^3: update values in one file from another
by Anonymous Monk on Dec 08, 2005 at 10:15 UTC
    If I wanted to change the logic of the above code so all values not in $fed{1} were incremented by 1 instead , how would I do this ?
    I tried doing this
    local @ARGV = ('file1.txt'); local $^I = '.bak'; while (<>) { m/^(\w+)\s+(\d+)$/; printf "$1\t%d\n", not exists $fed{$1} ? $2+1 : 0; }
    This only works the first time it's run, after that everything that isn't in $fed{1} is always only set to 1. I was trying to get it to increment all other values by 1 each time and set the $fed{1} values to 0
    I think my logic is screwed up somewhere ?
      My mistake, I realised how to solve it
      local @ARGV = ('file1.txt'); local $^I = '.bak'; while (<>) { m/^(\w+)\s+(\d+)$/; printf "$1\t%d\n", exists $fed{$1} ? 0 : $2+1; }