What I am trying to do is determine the difference between two sets of numbers only when a + is followed by a -. And then based on the difference value, to count those that are less than 100, 100-200, 201-500, 501-750, 751-1000, or greater than 1001 and also to determine how many didn't follow the rule (+ followed by -).
Based on the file above, I would assume the output would be:
<100 - 0
100-200 - 0
201-500 - 1
501-750 - 0
751-1000 - 0
>1001 - 2
Why do you need a hash for that? Just keep a list of differences and at the end sort through the list and loop over it, spitting out a report and resetting the count at the limits you have specified. While reading and calculating differences, increment a separate counter when you see a plus line, and decrement it when you see a minus line; this will be the count of unmatched plus lines.
so I could run it so it would search for + followed by a - and then take the difference between the two numbers.
How do I store the information so it knows to subtract out the two numbers when the expression is true? I guess this is why I was having a hard time with this.
You keep the previous value in a variable. As per your example, we don't need to worry about two consecutive lines with minuses on them.
while (<>) {
die "Invalid input" unless m/^(\d+) ([-+])$/);
my ($number, $sign) = ($1, $2); # as captured by the previous regex match
if ($sign eq '+') {
++$plusses;
$previous = $number;
next;
}
# else, must be a minus
--$plusses;
push @differences, $previous - $number;
}
Thank you era! It makes sense now. what i did was this
while (<>) {
chomp;
#die "Invalid input" unless m/^(\d+) ([-+])$/);
my ($number, $sign) = split("\t"); # as captured by the previous regex match
if ($sign eq '+') {
++$plusses;
$previous = $number;
next;
}
# else, must be a minus
--$plusses;
push @differences, $number - $previous;
print $number - $previous, "\n";
}
I wasn't sure if 'push @differences' was needed? So i just printed the values (I reversed the subtraction because I was getting negative numbers). I guess I can then use some if expressions to count each category.
dont know what I was thinking. the $plusses gives me the no match and I can use the difference in another expression to print it out. Great, exactly what i need :).