Are you sure $text is what you think it is? You can try to do a print "\n>$text<\n"; and see if it matches your expectations.
If $textis what you think it is, then how doesn't it work? What is your input, what is your expected output, what is your actual output? And with "actual output" I also mean warnings and errors. On that topic, is your script running with use strict; use warnings;?