Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

Perfect matching in perl

I have a problem about perfect matching.I want to get the sum of positive and negative integers from a file .Also I want to get dates have same values in the file.

My File:

Hello  -12, 3.4 and 32. Where did you
go on 01/01/2013 ? On 01/01/2013, we
went home. -4 plus 5 makes 1.
03/02/2013

Solution:

-16    //the sum of negative integers.
38     //the sum of positive integers.
2      //count of dates have same values.

My code:

    $sum=0;
    $sum1=0;
    while ($_=<>) {
        for each($_=~ /_d+g){
            $sum+=$_;
        }
        for each($_=~ /_d+(.| )/g){
            $sum1+=$_;
        }
        foreach($_=~ / d{2}(/d{2}({/d{4})?)?/ {
            $count++;
        }
    }
    print "$sum
";
    print "$sum1
";
    print "$count
";
} 

my code is wrong.Please help.I could not print above the results.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code is very broken. It includes lots of syntax errors, and you should include use strict; and use warnings; in EVERY script.

That said, I can help you a little bit by demonstrating how one would parse a file and pull out various regexes at the same time:

use strict;
use warnings;

while (<DATA>) {
    print "Processing: $_";

    while (m{(d{2}/d{2}/d{4})|(-d+)|(d+.?d*)}g) {
        my ($date, $neg, $pos) = ($1, $2, $3);
        if (defined $date) {
            print "  Found Date: $date
";
        } elsif (defined $neg) {
            print "  Found Neg: $neg
";
        } elsif (defined $pos) {
            print "  Found Pos: $pos
";
        }
    }
}

__DATA__
Hello  -12, 3.4 and 32. Where did you
go on 01/01/2013 ? On 01/01/2013, we
went home. -4 plus 5 makes 1.
03/02/2013

Outputs:

Processing: Hello  -12, 3.4 and 32. Where did you
  Found Neg: -12
  Found Pos: 3.4
  Found Pos: 32.
Processing: go on 01/01/2013 ? On 01/01/2013, we
  Found Date: 01/01/2013
  Found Date: 01/01/2013
Processing: went home. -4 plus 5 makes 1.
  Found Neg: -4
  Found Pos: 5
  Found Pos: 1.
Processing: 03/02/2013
  Found Date: 03/02/2013

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...