while ( ) { if ( /^(\d+\/123 11.*?) a / ) { #first matched my $first = $1; my $second = $1 if /\G.*?zyx(.*)/; #check for next match print "First = $first\n"; #print $second only if it is defined; print "Second = $second\n" if defined $second; } }