use strict; use warnings; my $count; # get $input from some place $input =~ s/^\s+//; # dump leading whitespace while ($input =~ s/[^\s]+\s+//) { ++$count; } ++$count if ($input =~ /./); # catch the last word