Search code examples
htmlperlescapingdouble-quotes

Perl: Escaping the double-quotes expanded from a variable


How can I get

my $name = 'John "FOO" Rambo';

expanded in

<span title=\"The great and mighty $name\"

To something like

<span title=\"The great and mighty John \"FOO\" Rambo\"</span>

rather than

<span title=\"The great and mighty John "FOO" Rambo\"

So that my html tag is not corrupted when generating a page and the name contains " ?


Solution

  • The proper HTML would be the following:

    <span title="The great and mighty John &quot;FOO&quot; Rambo">...</span>
    

    You can obtain it using the following:

    use HTML::Entities qw( encode_entities );
    
    my $html = '<span title="' . encode_entities("The great and mighty $name") . '">...</span>';
       -or-
    my $html = '<span title="The great and mighty ' . encode_entities($name) . '">...</span>';
    

    You should probably be using a template system. Were you to use Template-Toolkit, the template would be

    <span title="The great and mighty [% name | html %]">...</span>