#!usr/bin/perl use strict; use warnings; my $line_total=0; my $total = 0; my $current_bucket = undef; while (my $line = ) { my ($bucket, $num) = $line =~ m/^\s*(\d+)\s*\|\s*(\d+)/; if (!defined($current_bucket)) # start the first "bucket". # use of defined() instead of zero # as a flag allows for a "zero" # bucket which I added as a # test case. { $line_total = $num; $current_bucket = $bucket; } elsif ($bucket == $current_bucket) # "normal" case { $line_total += $num; } else # a new "bucket" starts... { # output current bucket's results print "Line $current_bucket = $line_total\n"; $total += $line_total; # We've already read a line for the next bucket. # Adjust values to start $line_total running for this # new "bucket" $line_total = $num; $current_bucket = $bucket; } } # print the last bucket's results to finalize output: print "Line $current_bucket = $line_total\n"; $total += $line_total; ## This is the total result print "total=$total\n"; =Prints Line 0 = 10 Line 1 = 150 Line 2 = 75 Line 3 = 55 total=290 =cut __DATA__ 0|10 1|10 1|20 1|30 1|40 1|50 2|15 2|25 2|35 3|1 3|2 3|3 3|4 3|5 3|6 3|7 3|8 3|9 3|10