in reply to update values in one file from another

This is my bet at it:

use warnings; use strict; my %fed; open my $fd, '<', 'file2' or die "open: $!"; $fed{$1}++ while <$fd> =~ m/^(\w+)\s/; close $fd; open $fd, '<', 'file1' or die "open: $!"; open my $fd2, '>', '/tmp/file1.tmp' or die "open: $!"; ## FIXME: tmpf +ile while (<$fd>) { m/^(\w+)\s+(\d+)$/; printf $fd2 "$1\t%d\n", exists $fed{$1} ? $2+1 : $2; } close $fd2; close $fd; rename '/tmp/file1.tmp', 'file1' or warn "rename: $!";

I've tried editing file1 inplace using $^I and <> but didn't get anything.

--
David Serrano

Replies are listed 'Best First'.
Re^2: update values in one file from another
by GrandFather (Saint) on Dec 07, 2005 at 10:13 UTC

    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

      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

      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
      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; }