Skip to content Skip to sidebar Skip to footer

Number Appearing In Perl-generated Javascript Code Instead Of "$("

On a site I'm working on there are random numbers appearing in a very simple bit of jQuery. Instead of what's meant to appear, these numbers — 48, etc. — appear at the

Solution 1:

$( is a Perl predefined variable, expanding to the process's group ID list.

If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by getgid() , and the subsequent ones by getgroups() , one of which may be the same as the first number.

See the perlvar docs for details.

To avoid the problem, make sure to escape $( (and any other JavaScript $ chars) in Perl strings, or use '' instead of "" to avoid interpolation.

Bad:

$html = "$(document).ready(...)";

Good:

$html = "\$(document).ready(...)";
$html = '$(document).ready(...)';

In the code above, for example, the script section should be:

<script type="text/javascript">
  \$(document).ready(function () {
    \$(".closed").click(function () {

      \$(this).find("div.but").toggleClass('plus').toggleClass('minus');
      \$(this).toggleClass('closed').toggleClass('open');

    });    
  });
</script>

Solution 2:

In addition to Paul's escaping suggestions above, I prefer to use the alternate quoting method you used above so I don't have to escape every string and quote in my Javascript. Enclosing a string in q{} will save you from having to escape every dollar sign. So long as you don't need interpolation in that block you'll be fine!

So your code could be written as:

$web_content .= q{
   <scripttype="text/javascript">
    $(document).ready(function () {
        $(".closed").click(function () {


             $(this).find("div.but").toggleClass('plus').toggleClass('minus');

             $(this).toggleClass('closed').toggleClass('open');

        });

    });

    </script>
};

Solution 3:

since you are generating the code via Perl, $( is a reserved one in Perl. Put it in a variable in give a string concatenation.

Documentation

Since Perl 5.6, Perl variable names may be alphanumeric strings that begin with control characters (or better yet, a caret). These variables must be written in the form ${^Foo} ; the braces are not optional. ${^Foo} denotes the scalar variable whose name is a control-F followed by two o 's. These variables are reserved for future special uses by Perl, except for the ones that begin with ^_ (control-underscore or caret-underscore). No control-character name that begins with ^_ will acquire a special meaning in any future version of Perl; such names may therefore be used safely in programs. $^_ itself, however, is reserved.

Solution

Use either of these:

"\$(document).ready(...)";
'$(document).ready(...)';

Post a Comment for "Number Appearing In Perl-generated Javascript Code Instead Of "$(""