Subject: | Backslashes in strings not properly escaped |
I was dumping an anonymous hash holding a value with a backslash in it. The string was dumped like this: "C:\", escaping the quote and causing a syntax error. I added a line to the anon_scalar method:
$value =~ s/\\/\\\\/g;
which solves this problem.
package Data::JavaScript::Anon;
# This package provides a mechanism to convert the main basic Perl structures
# into JavaScript structures, making it easier to transfer data
# from Perl to JavaScript.
use strict;
use UNIVERSAL 'isa';
use vars qw{$VERSION $errstr $RE_NUMERIC $RE_NUMERIC_HASHKEY};
BEGIN {
$VERSION = '0.3';
$errstr = '';
# Attempt to define a single, all encompasing,
# regex for detecting a legal JavaScript number.
# We do not support the exotic values, such as Infinite and NaN.
my $_sci = qr/[eE](?:\+|\-)?\d+/; # The scientific notation exponent ( e.g. 'e+12' )
my $_dec = qr/\.\d+/; # The decimal section ( e.g. '.0212' )
my $_int = qr/(?:[1-9]\d*|0)/; # The integers section ( e.g. '2312' )
my $real = qr/(?:$_int(?:$_dec)?|$_dec)(?:$_sci)?/; # Merge the integer, decimal and scientific parts
my $_hex = qr/0[xX][0-9a-fA-F]+/; # Hexidecimal notation
my $_oct = qr/0[0-8]+/; # Octal notation
# The final combination of all posibilities for a straight number
# The string to match must have no extra characters
$RE_NUMERIC = qr/^(?:\+|\-)??(?:$real|$_hex|$_oct)$/;
# The numeric for of the hash key is similar, but without the + or - allowed
$RE_NUMERIC_HASHKEY = qr/^(?:$real|$_hex|$_oct)$/;
}
#####################################################################
# Top Level Dumping Methods
sub anon_dump {
my $class = shift;
my $something = shift;
my $processed = shift || {};
# Handle the undefined case
return 'undefined' unless defined $something;
# Handle the basic non-reference case
return $class->anon_scalar( $something ) unless ref $something;
# Check to see if we have processed this reference before.
# This should catch circular, cross-linked, or otherwise complex things
# that we can't handle.
if ( $processed->{$something} ) {
return $class->_err_found_twice( $something );
} else {
$processed->{$something} = 1;
}
# Handle the SCALAR reference case, which in our case we treat
# like a normal scalar.
if ( isa( $something, 'SCALAR' ) ) {
return $class->anon_scalar( $something );
}
# Handle the array case by generating an anonymous array
if ( isa( $something, 'ARRAY' ) ) {
# Create and return the array
my $list = join ', ', map { $class->anon_dump($_, $processed) } @$something;
return "[ $list ]";
}
# Handle the hash case by generating an anonymous object/hash
if ( isa( $something, 'HASH' ) ) {
# Create and return the anonymous hash
my $pairs = join ', ', map {
$class->anon_hash_key( $_ )
. ': '
. $class->anon_dump( $something->{$_}, $processed )
} keys %$something;
return "{ $pairs }";
}
$class->_err_not_supported( $something );
}
# Same thing, but creating a variable
sub var_dump {
my $class = shift;
my $name = shift or return undef;
my $value = $class->anon_dump( shift );
"var $name = $value;";
}
# Wrap some JavaScript in a HTML script tag
sub script_wrap {
"<script language=\"JavaScript\" type=\"text/JavaScript\">\n"
. "<!--\n\n$_[1]\n// -->\n"
. "</script>";
}
# Is a particular string a legal JavaScript number.
# Returns true if a legal JavaScript number.
# Returns false otherwise.
sub is_a_number {
my $class = shift;
my $number = (defined $_[0] and ! ref $_[0]) ? shift : '';
$number =~ m/$RE_NUMERIC/ ? 1 : '';
}
#####################################################################
# Basic Variable Creation Statements
# Create a Javascript scalar given the javascript variable name
# and a reference to the scalar.
sub var_scalar {
my $class = shift;
my $name = shift or return undef;
my $scalar_ref = isa( $_[0], 'SCALAR' ) ? shift : return undef;
my $value = $class->js_value( $$scalar_ref ) or return undef;
"var $name = $value;";
}
# Create a Javascript array given the javascript array name
# and a reference to the array.
sub var_array {
my $class = shift;
my $name = shift or return undef;
my $array_ref = isa( $_[0], 'ARRAY' ) ? shift : return undef;
my $list = join ', ', map { $class->anon_dump($_) } @$array_ref;
"var $name = new Array( $list );";
}
# Create a Javascript hash ( which is just an object ), given
# the variable name, and a reference to a hash.
sub var_hash {
my $class = shift;
my $name = shift or return undef;
my $hash_ref = isa( $_[0], 'HASH' ) ? shift : return undef;
my $struct = $class->anon_hash( $hash_ref ) or return undef;
"var $name = $struct;";
}
#####################################################################
# Basic Serialisation And Escaping Methods
# Turn a single perl value into a single javascript value
sub anon_scalar {
my $class = shift;
my $value = isa( $_[0], 'SCALAR' ) ? ${shift()} : shift;
return 'null' unless defined $value;
# Don't quote if it is numeric
return $value if $value =~ /$RE_NUMERIC/;
$value =~ s/\\/\\\\/g;
$value =~ s/"/\\"/g;
'"' . $value . '"';
}
# Turn a single perl value into a javascript hash key
sub anon_hash_key {
my $class = shift;
my $value = (defined $_[0] and ! ref $_[0]) ? shift : return undef;
# Don't quote if it is just a set of word characters or numeric
return $value if $value =~ /^[^\W\d]\w*$/;
return $value if $value =~ /$RE_NUMERIC_HASHKEY/;
# Escape and quote
$value =~ s/"/\\"/g;
'"' . $value . '"';
}
# Create a Javascript array given the javascript array name
# and a reference to the array.
sub anon_array {
my $class = shift;
my $name = shift or return undef;
my $array_ref = isa( $_[0], 'ARRAY' ) ? shift : return undef;
my $list = join ', ', map { $class->anon_scalar($_) } @$array_ref;
"[ $list ]";
}
# Create a Javascript hash ( which is just an object ), given
# the variable name, and a reference to a hash.
sub anon_hash {
my $class = shift;
my $name = shift or return undef;
my $hash_ref = isa( $_[0], 'HASH' ) ? shift : return undef;
my $pairs = join ', ', map {
$class->anon_hash_key( $_ )
. ': '
. $class->anon_scalar( $hash_ref->{$_} )
} keys %$hash_ref;
"{ $pairs }";
}
#####################################################################
# Utility and Error Methods
sub _err_found_twice {
my $class = shift;
my $something = ref $_[0] || 'a reference';
$errstr = "Found $something in your dump more than once. "
. "Data::JavaScript::Anon does not support complex, "
. "circular, or cross-linked data structures";
undef;
}
sub _err_not_supported {
my $class = shift;
my $something = ref $_[0] || 'A reference of unknown type';
$errstr = "$something was found in the dump struct. "
. "Data::JavaScript::Anon only supports objects based on, "
. "or references to SCALAR, ARRAY and HASH type variables.";
undef;
}
1;
__END__
=head1 NAME
Data::JavaScript::Anon - Create big, dumb and/or anonymous data structures in JavaScript
=head1 SYNOPSIS
# Dump an arbitrary structure to javascript
Data::JavaScript::Anon->anon_dump( [ 'a', 'b', { a => 1, b => 2 } ] );
=head1 DESCRIPTION
Data::JavaScript::Anon provides the ability to dump large simple data
structures to JavaScript. That is, things that don't need to be a class,
or have special methods or whatever.
The method it uses is to write anonymous variables, in the same way you
would in Perl. The following shows some examples.
# Perl anonymous array
[ 1, 'a', 'Foo Bar' ]
# JavaScript equivalent ( yes, it's exactly the same )
[ 1, 'a', 'Foo Bar' ]
# Perl anonymous hash
{ foo => 1, bar => 'bar' }
# JavaScript equivalent
{ foo: 1, bar: 'bar' }
One advantage of doing it in this method is that you do not have to
co-ordinate variable names between your HTML templates and Perl. You
could use a simple Template Toolkit phrase like the following to get
data into your HTML templates.
var javascript_data = [% data $];
In this way, it doesn't matter WHAT the HTML template calls a
particular variables, the data dumps just the same. This could help
you keep the work of JavaScript and Perl programmers ( assuming you
were using different people ) seperate, without creating
cross-dependencies between their code, such as variable names.
The variables you dump can also be of arbitrary depth and complexity,
with a few limitations.
=over 4
=item ARRAY and HASH only
Since arrays and hashs are all that is supported by JavaScript, they
are the only things you can use in your structs. Any references or a
different underlying type will be detected and an error returned.
Note that Data::JavaScript::Anon will use the UNDERLYING type of the
data. This means that the blessed classes or objects will be ignored
and their data based on the object's underlying implementation type.
This can be a positive thing, as you can put objects for which you expect
a certain dump structure into the data to dump, and it will convert to
unblessed, more stupid, JavaScript objects cleanly.
=item No Circular References
Since circular references can't be defined in a single anonymous struct,
they are not allowed. Try something like L<Data::JavaScript> instead.
Although not supported, they will be detected, and an error returned.
=back
=head1 MAIN METHODS
All methods are called as methods directly, in the form
C<< Data::JavaScript::Anon->anon_dump( [ 'etc' ] ) >>.
=head2 anon_dump STRUCT
The main method of the class, anon_dump takes a single arbitrary data
struct, and converts it into an anonymous JavaScript struct.
If needed, the argument can even be a normal text string, although it
wouldn't do a lot to it. :)
Returns a string containing the JavaScript struct on success, or C<undef>
if an error is found.
=head2 var_dump $name, STRUCT
As above, but the C<var_dump> method allows you to specify a variable name,
with the resulting JavaScript being C<var name = struct;>. Note that the
method WILL put the trailing semi-colon on the string.
=head2 script_wrap $javascript
The C<script_wrap> method is a quick way of wrapping a normal JavaScript html
tag around your JavaScript.
=head2 is_a_number $scalar
When generating the javascript, numbers will be printed directly and not
quoted. The C<is_a_number> method provides convenient access to the test
that is used to see if something is a number. The test handles just about
everything legal in JavaScript, with the one exception of the exotics, such
as Infinite, -Infinit and NaN.
Returns true is a scalar is numberic, or false otherwise.
=head1 SECONDARY METHODS
The following are a little less general, but may be of some use.
=head2 var_scalar $name, \$scalar
Creates a named variable from a scalar reference.
=head2 var_array $name, \@array
Creates a named variable from an array reference.
=head2 var_hash $name, \%hash
Creates a named variable from a hash reference.
=head2 anon_scalar \$scalar
Creates an anonymous JavaScript value from a scalar reference.
=head2 anon_array \@array
Creates an anonymous JavaScript array from an array reference.
=head2 anon_hash \%hash
Creates an anonymous JavaScript object from a hash reference.
=head2 anon_hash_key $value
Applys the formatting for a key in a JavaScript object
=head1 SUPPORT
Bugs should be reported via the CPAN bug tracker at:
http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Data%3A%3AJavaScript%3A%3AAnon
For other comments or queries, contact the author.
=head1 AUTHOR
Adam Kennedy (Maintainer), L<http://ali.as/>, cpan@ali.as
=head1 COPYRIGHT
Copyright (c) 2003 Adam Kennedy. All rights reserved.
This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the
LICENSE file included with this module.
=cut