use strict; use warnings; my $string = " a 1 # "; while ($string =~ /\G(?: (\s+) | ([0-9]+) | (\w+))/xgc) { if (defined $1) { print "whitespace\n"; } elsif (defined $2) { print "integer\n"; } elsif (defined $3) { print "word\n"; } }