sub parse { if ( $_[0] =~ /\[(.*)$/ ) { parse($1)} else { if ($_[0] =~ /(.*)\]/ ) { #Do your replace on $1 }else{ die "Unmatched brackets found"; } } }