while( defined my $record = ) { if( $record =~ m/(?x) \A ## anchor the match to the beginning of the record printer \s+ ## match the word 'printer', and one or more spaces (?: \w+ \s+ ){2} ## match two words followed by spaces idle \. \s+ ## match the word 'idle', followed by a period and spaces enabled \s+ ## match the word 'enabled', followed by spaces / ) { ## $record matched, do your thing... } } #### .