documentationify
[scpubgit/HTML-String.git] / lib / HTML / String / Overload.pm
1 package HTML::String::Overload;
2
3 use strictures 1;
4 use HTML::String::Value;
5 use B::Hooks::EndOfScope;
6 use overload ();
7
8 sub import {
9     my ($class, @opts) = @_;
10     overload::constant q => sub {
11         HTML::String::Value->new($_[1], @opts);
12     };
13     on_scope_end { __PACKAGE__->unimport };
14 }
15
16 sub unimport {
17     overload::remove_constant('q');
18 }
19
20 1;
21
22 __END__
23
24 =head1 NAME
25
26 HTML::String::Overload - Use constant overloading with L<HTML::String>
27
28 =head1 SYNOPSIS
29
30   use HTML::String::Overload;
31   
32   my $html = '<h1>'; # marked as HTML
33   
34   no HTML::String::Overload;
35
36   my $text = '<h1>'; # not touched
37   
38   my $html = do {
39     use HTML::String::Overload;
40   
41     '<h1>'; # marked as HTML
42   };
43   
44   my $text = '<h1>'; # not touched
45
46 =head1 DESCRIPTION
47
48 This module installs a constant overload for strings - see
49 L<overload/Overloading constants> in overload.pm's docs for how that works.
50
51 On import, we both set up the overload, and use L<B::Hooks::EndOfScope> to
52 register a callback that will remove it again at the end of the block; you
53 can remove it earlier by unimporting the module using C<no>.
54
55 =head1 CAVEATS
56
57 Due to a perl bug (L<https://rt.perl.org/rt3/Ticket/Display.html?id=49594>),
58 you can't use backslash escapes in a string to be marked as HTML, so
59
60   use HTML::String::Overload;
61   
62   my $html = "<h1>\n<div>foo</div>\n</h1>";
63
64 will not be marked as HTML - instead you need to write
65
66   my $html = '<h1>'."\n".'<div>foo</div>'."\n".'</h1>';
67
68 which is annoying, so consider just using L<HTML::String> and doing
69
70   my $html = html("<h1>\n<div>foo</div>\n</h1>");
71
72 in that case.
73
74 The import method we provide does actually take extra options for constructing
75 your L<HTML::String::Value> objects but I'm not yet convinced that's a correct
76 public API, so use that feature at your own risk (the only example of this is
77 in L<HTML::String::TT::Directive>, which is definitely not user serviceable).
78
79 =head1 AUTHORS
80
81 See L<HTML::String> for authors.
82
83 =head1 COPYRIGHT AND LICENSE
84
85 See L<HTML::String> for the copyright and license.
86
87 =cut