Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

The file is text file:
A|10
B|20
C|20
D|40
and so on.

I need print out the results like:
A+B=30
A+B+C=50
C+A+D=70
and more.

  • Comment on How do read the varibles from a files and do some calculation

Replies are listed 'Best First'.
Re: How do read the varibles from a files and do some calculation
by ikegami (Patriarch) on Oct 21, 2004 at 17:24 UTC
    my %symtab; while (<FILE>) { chomp; if (/^(\w+)\|(\d+)$/) { $symtab{$1} = $2; } else { # Error } } print($symtab{A} + $symtab{B}, $/); print($symtab{A} + $symtab{B} + $symtab{C}, $/); print($symtab{C} + $symtab{A} + $symtab{D}, $/);

    Like this, or do you need to parse the equations too? Update: Here's a version that parses sums too:

    my %symtab; while (<DATA>) { chomp; if (/^(\w+)\|(\d+)$/) { $symtab{$1} = $2; } else { # Error } } foreach ( 'A+B', 'A+B+C', 'C+A+D', ) { my $sum = 0; foreach (split(/\+/, $_)) { my $ident = $_; $ident =~ s/^\s+//; $ident =~ s/\s+$//; if (exists($symtab{$ident})) { $sum += $symtab{$ident}; } else { # Error } } print("$_=$sum$/"); } __DATA__ A|10 B|20 C|20 D|40
Re: How do read the varibles from a files and do some calculation
by pg (Canon) on Oct 21, 2004 at 17:48 UTC

    Probably it is better to simply use split, so that you don't need to worry about things like the format of the number.

    use strict; use warnings; my ($A, $B, $C, $D); while (<DATA>) { chomp; my @parts = split /\|/; print "\$$parts[0] = $parts[1]\n"; eval("\$$parts[0] = $parts[1]"); } print "$A\n"; print "$B\n"; print "$C\n"; print "$D\n"; __DATA__ A|-10 B|20_000 C|20.1234 D|2E-3

    Then you can do whatever you want with those variables.

      If he wants a more flexible number format than \d+, one of the perlfaqs gives a regexp that matches what Perl considers a number.

      Your code handles A|system("rm -rf /") quite interestingly. If you call that a feature (plausible), then A|$B||$C is buggy. Using split(/\|/, $_, 2) instead of the current split solves it.

      Your code also handles A = system("rm -rf /")|0 quite interestingly, and I can't see that being called a feature.

        one of the perlfaqs gives a regexp that matches what Perl considers a number

        That would be perldoc -q whole, also available online.

How to read 2 files and do the calculations
by Anonymous Monk on Oct 21, 2004 at 22:27 UTC
    File A:
    Product Price
    AAA|10
    BBB|20
    CCC|30
    DDD|40
    more

    File B:
    Group Name: Small
    Junk: lll
    Product Name:
    AAA
    BBB
    Group Name: Big
    Junk: ggg
    Product Name:
    AAA
    CCC
    DDD
    more<bg> I need to print out:<br Group Small:
    AAA 10
    BBB 20
    Total 20
    Group Big:
    AAA 10
    CCC 30
    DDD 40
    Total 80 Thanks!