$_ = q~ one one two one two 3 ~; while( /(one) (two)( 3)?/gs ){ print 'Got 1 ', $1,"\n" if defined $1; print 'Got 2 ', $2,"\n" if defined $2; print 'Got 3 ', $3,"\n" if defined $3; print "----\n"; } __END__ Got 1 one Got 2 two ---- Got 1 one Got 2 two Got 3 3 ----