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

Hello, I have created a few website scripts that accept user input. However, to make the user input HTML-safe, I am replacing all < signs with &lt; and replacing all > signs with &gt;.

This works fine if there is only one variable, as such:

$name =~ s/\</\&lt\;/g $name =~ s/\>/\&gt\;/g

But what if there are twenty variables, such as name, location, age, favorite movies, favorite books, etc.? Is there an easier way to edit all twenty variables rather than pasting the above two lines of code twenty times?

Thanks in advance for all of your help.

Replies are listed 'Best First'.
Re: how do I edit multiple variables at once?
by GrandFather (Saint) on Jul 04, 2009 at 04:46 UTC

    You should seriously consider using a suitable module (HTML::Entities for example) for manipulating HTML entities. There are more symbols than just < and > to be concerned about.


    True laziness is hard work
      Thank you so much for the response. However, HTML::Entities does not filter a single quote: '

      The four main symbols I would be concerned about are <, >, " and '. Do you by any chance know of a filter that takes care of all these?

      Update a few minutes later: whoops! I'm sorry. HTML::Entities actually can take care of the single quote. I didn't see this until I read the entire documentation. Thanks again!

Re: how do I edit multiple variables at once?
by liverpole (Monsignor) on Jul 04, 2009 at 03:08 UTC
    Hi keiusui,

    I would suggest using a hash (or, as in the following example, a hash reference) to contain those variables, in conjunction with map, like this:

    use strict; use warnings; my $h_vars = { 'name' => '<h1>Fred Flintstone</h1>', 'location' => 'Bedrock', 'favorite movie' => 'One <i>Million</i> Years B.C.', 'favorite book' => 'Danny the <b>Dinosaur</b>', }; map { s/\</\&lt\;/g; s/\>/\&gt\;/g } values %$h_vars; # Test code use Data::Dumper; printf "Results %s\n", Dumper($h_vars); __END__ Results $VAR1 = { 'location' => 'Bedrock', 'favorite movie' => 'One &lt;i&gt;Million&lt;/i&gt; Years B. +C.', 'name' => '&lt;h1&gt;Fred Flintstone&lt;/h1&gt;', 'favorite book' => 'Danny the &lt;b&gt;Dinosaur&lt;/b&gt;' };

    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
      Please.
      map { s/\</\&lt\;/g; s/\>/\&gt\;/g } values %$h_vars;
      No void maps please. This is even shorter:
      s/\</\&lt\;/g, s/\>/\&gt\;/g for values %$h_vars;

      -- Randal L. Schwartz, Perl hacker

      The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.