use strict; use warnings; use feature "state"; while (my ($aa, $bb) = iter()) { last unless defined $bb; my $diff = $2 - $1 if "$aa $bb" =~ /(\d+)[^\d]*(\d+)/; print "$aa ; $bb => $diff\n"; } sub iter { state @a_buff; while (){ chomp; push @a_buff, $_ and next if /a/; return shift @a_buff, $_; } } __DATA__ a 123 ...