$$file =~ s/<%[ ]*link_name[ ]*([^ ]*)[ ]*%>(?{push(@link_names,$1);})/<% link_name $1%>/g; #can be rewritten as (changed single space to \s, might # be more usefull $$file =~ s{ <% \s* link_name \s* (\S*) \s* %> }{ push @link_names,$1; "<% link_name $1 %>" }xg; # but in fact you don't even need s/// while($$file =~ m{ <% \s* link_name \s* (\S*) \s* %> }xg ){ push @link_names,$1 }