jeteve has asked for the wisdom of the Perl Monks concerning the following question:

Hi fellow monks.

Just a quick question: Is there a way to specify the encoding as html entities for a file handler ?

What I like to do is :

binmode STDOUT , ":html" ;

-- Nice photos of naked perl sources here !

Replies are listed 'Best First'.
Re: binmode html encoding
by gellyfish (Monsignor) on Aug 09, 2006 at 10:46 UTC

    You can do this with a simple module, The following is adapted from PerlIO::via::QuotedPrint and can be installed into the same directory as that module.

    package PerlIO::via::HtmlEncode; $VERSION = '0.01'; use strict; use HTML::Entities; 1; sub PUSHED { bless \*PUSHED,$_[0] } sub FILL { my $line = readline( $_[1] ); (defined $line) ? decode_entities( $line ) : undef; } sub WRITE { (print {$_[2]} encode_entities($_[1])) ? length($_[1]) : -1; } 1;
    and then you can just do something like:
    use PerlIO::via::HtmlEncode; + binmode STDOUT,':via(HtmlEncode)'; + print "&£<>";

    If I get a minute I could package that and upload it to CPAN.

    /J\

Re: binmode html encoding
by Leviathan (Scribe) on Aug 09, 2006 at 10:00 UTC

    You probably can get away with tieing the filehandle with Tie::Handle. Here's an example:

    package html; require Tie::Handle; @ISA = qw/Tie::Handle/; use HTML::Entities; sub TIEHANDLE { return bless({}, shift); } sub PRINT { untie *STDOUT; print encode_entities(join "", @_); tie *STDOUT, "html"; } package main; tie *STDOUT, "html"; print "foo & bar\n";

    It might need some work to plug cleanly in whatever code you need to write.

    --
    Leviathan.