views:

139

answers:

3

Looking for a simple way to HTML encode a string/object in perl. the least amount of additional packages used the better.

+1  A: 
use HTML::Entities;

print encode_entities(<>);
Anon.
+6  A: 

HTML::Entities is your friend here.

use HTML::Entities;
my $encoded = encode_entities( "foo & bar & <baz>" );
friedo
+3  A: 

Which do you need to encode, a string or an object? If it's just a string, then you should just have to worry about encoding issues such as UTF-8, and CGI::escape will probably do the trick for you. If it's an object, you'll need to serialize it first, which opens up a whole new set of issues, but you might want to consider JSON-encoding it.

PS. Although since I can't find any recent documentation on this method (it's actually imported from CGI::Util and is marked as "internal"), you should probably use escapeHTML() as daxim points out in his comment: http://search.cpan.org/perldoc?CGI#AUTOESCAPING_HTML

Ether
The function is called `escapeHTML`. Proper deeplink: http://search.cpan.org/perldoc?CGI#AUTOESCAPING_HTML
daxim
@daxim: `CGI::escape` very much exists; it's actually defined in CGI::Util and imported into CGI proper. If you look at the source there are some subtle differences in implementation, which are sadly not well described in the documentation.
Ether
Alright. I'm not able to undo the vote because it is too old.
daxim
@daxim: I've edited the post so you get another crack at that vote :)
Ether