# global lookup hash my %ESCAPES = ( '&' => '&', '<' => '<', '>' => '>', '"' => '"', ); # the subroutine sub xml_encode { my ($str) = @_; $str =~ s/([&<>"])/$ESCAPES{$1}/ge; return $str; } # and invoke it like $data = xml_encode($data);