if ( $contents =~ /^line3/mo ) { if ( $contents =~ /^line2-(\w*)/mo ) { print $1; # has to be changed as well } }