use strict; use warnings; # Create a test file open outFile, ">", "file1.txt"; print outFile <<end; rabbit 1 hen 0 pig 2 cow 2 sheep 5 end close outFile; #Sample code open inFile, "<", "file1.txt" or die "Unable to read file1.txt. $!"; my @lines = <inFile>; close inFile; my %animals; # build a hash keyed by animal with the count as value map {/(\w+)\s+(\d+)/; $animals{$1}=$2} @lines; # Production code would use file2 rather than DATA while (<DATA>) { /(\w+)/; #Assume animal is always the first thing on the line # Bump animal count - creates new entry if new animal ++$animals{$1} if defined $1; } open outFile, ">", "file1.txt"; for (@lines) { /(\w+)/; printf outFile "%-6s %d\n", $1, $animals{$1}; $animals{$1} = 0; # Tag as printed } #add any new animals to the end of the file for (keys %animals) { next if ! $animals{$_}; printf outFile "%-6s %d\n", $_, $animals{$_}; } close outFile; __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

Creates a file containing:

rabbit 2 hen 0 pig 2 cow 3 sheep 6

DWIM is Perl's answer to Gödel

In reply to Re: update values in one file from another by GrandFather
in thread update values in one file from another by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.