in reply to Extract varibles from 2 text files and make a report

fileA.txt contains what you listed as File A in the question. I put the content of File B into __DATA__.

#!/usr/local/bin/perl -w use strict; my(%products) = (); open(my $fh, '<', './fileA.txt') || die "Could not read fileA.txt: $!\ +n"; while(<$fh>){ chomp; my($key, $value)=split(/\|/); $products{$key} = $value; } close($fh); my(@groups)=(); { local $/; my $string = <DATA>; @groups = split(/(?=Group)/, $string); } foreach (@groups){ my $name; if(m/Group Name: (.+)/){ $name = $1; }else{ print STDERR "Could not find group name\n"; next; } my(@prods); if(m/Product Name:\n(.*)\Z/ms){ my $prod = $1; @prods = split(/\n/, $prod); }else{ print "$name\n"; print STDERR "Group $name didn't have any products\n"; next; } print "Group ".$name."\n"; my $total = 0; foreach (@prods){ print "$_ $products{$_}\n"; $total += $products{$_}; } print "Total ".join('+', @prods)." = $total\n"; } __DATA__ Group Name: Small Junk: lll Product Name: AAA BBB Group Name: Big Junk: ggg Product Name: AAA CCC DDD #output Group Small AAA 10 BBB 20 Total AAA+BBB = 30 Group Big AAA 10 CCC 30 DDD 40 Total AAA+CCC+DDD = 80
May the Force be with you

Replies are listed 'Best First'.
Re^2: Extract varibles from 2 text files and make a report
by Anonymous Monk on Oct 26, 2004 at 17:51 UTC
    If the File B like:
    Group Name: Small
    Junk: lll
    Product Name:
    AAA "This is test1 for me."
    BBB "This may be I like it."
    Group Name: Big
    Junk: ggg
    Product Name:
    AAA "This is t2."
    CCC "This should be ok"
    DDD "This is the last one. we shoud have more."

    How do I split the string of each product? The output is same as before.

      If your goal is to discard everything following "AAA" or "BBB", and so on, you could modify the split statement to look like this:

      @prods = split(/\s[^\n]+\n/, $prod);

      This will remove everything following the first whitespace character in each of the lines following "Product Name:". Is that what you were trying to do?

      May the Force be with you
        That is what I want. Thanks. But if there is some spaces infront of AAA and BBB what should I do?
        Thank you!!!
        But if there are some spaces before "AAA" or "BBB" what should I do. How do you find the reference on using "split"? Thank you!