^
and $
on either side of a newline within a string (instead of just at the start and end of the string). #!/usr/bin/perl -w $string = ''; # put the whole file in $string while(<>) { $string .= $_ } while($string =~ /^\S+/mg){ print "[$&] " } print "\n";