Data-JavaScript-Anon

 view release on metacpan or  search on metacpan

lib/Data/JavaScript/Anon.pm  view on Meta::CPAN

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 5.006;
use strict;
use warnings;
use Params::Util   qw{ _STRING _SCALAR0 _ARRAY0 _HASH0 };
use Class::Default ();

use vars qw{@ISA $VERSION $errstr $RE_NUMERIC $RE_NUMERIC_HASHKEY %KEYWORD};
BEGIN {
	$VERSION = '1.03';
	@ISA     = 'Class::Default';
	$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-7]+/;                             # 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)\z/;

	# The numeric for of the hash key is similar, but without the + or - allowed
	$RE_NUMERIC_HASHKEY = qr/^(?:$real|$_hex|$_oct)\z/;

	%KEYWORD = map { $_ => 1 } qw{
		abstract boolean break byte case catch char class const
		continue debugger default delete do double else enum export
		extends false final finally float for function goto if
		implements import in instanceof int interface long native new
		null package private protected public return short static super
		switch synchronized this throw throws transient true try typeof
		var void volatile while with
	};
}





#####################################################################
# Top Level Dumping Methods

sub new {
	my $proto = shift;
	my $class = ref $proto || $proto;
	my $opts  = _HASH0($_[0]) ? shift : { @_ };

	# Create the object
	my $self = bless {
		quote_char => '"',
	}, $class;

	## change the default quote character
	if ( defined $opts->{quote_char} && length $opts->{quote_char} ) {
		$self->{quote_char} = $opts->{quote_char};
	}

	return $self;
}

sub _create_default_object {
	my $class = shift;
	my $self  = $class->new();
	return $self;
}

sub anon_dump {
	my $class     = shift;
	my $something = shift;
	my $processed = shift || {};

lib/Data/JavaScript/Anon.pm  view on Meta::CPAN

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 numeric, or false otherwise.

You may also access method in using an instantiated object.

=head2 new HASH

This will create a Data::JavaScript::Anon object that will allow you to change
some of the default behaviors of some methods.

    Options:
        quote_char  : Set the quote_char for stirng scalars. Default is '"'.

=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:

L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Data-JavaScript-Anon>

For other comments or queries, contact the author.

=head1 AUTHOR

Adam Kennedy E<lt>adamk@cpan.orgE<gt>

=head1 SEE ALSO

L<JSON>, L<http://ali.as/>



( run in 0.702 second using v1.01-cache-2.11-cpan-6b5c3043376 )