CleanCode Perl Libraries
Multi-Lingual Library Maintainability
available: Perl not available: Java not available: JavaScript available: Certified
Class
not available: Testable
Class
not available: Standalone
Mode
available: Diagnostic
Enabled

NAME

Convert::SimpleJs2Perl - Converts JavaScript into Perl.

SYNOPSIS

        use Convert::SimpleJs2Perl;
        $js2p = Convert::SimpleJs2Perl->new(
                "/lib/perl", "Sys::LibPackage", "/lib/js/mylib.js", 1);
        return $js2p->convertFile();

REQUIRES

Perl5.005, File::stat, File::Handy, Data::Diagnostic

DESCRIPTION

This translator is deemed simple because the translation process is simply a series of regular expression substitutions, rather than a genuine parser-based process. The intent of this module is to translate definitions rather than arbitrary code (which would be quite a challenging task!), which it does reasonably well, when abiding by the formatting constraints imposed. This allows creating a single set of of definitions used both on the client side and the server side of a CGI program.

This module converts a limited subset of Javascript into Perl, saves the Perl in a module, and loads the resulting module. If the output file already exists, it is renamed from file.pm to file.bak. If the load fails, file.pm is renamed to file.BAD so the suspect code may be reviewed, and file.bak is renamed back to file.pm. The backup and corrupt file extensions are configurable via the setFileExtensions method.

The conversion step is skipped if the Perl file is up to date with (that is, is newer than) the JavaScript file. Alternately, conversion may be forced each time via the setAlwaysCreate method.

Translation Details

SimpleJs2Perl expects each property or variable definition on a separate line. (The term property refers to an object property or hash key-value pair.) Also, each property must be wholly contained on one line. Variable definitions, though, may cross multiple lines.

SimpleJs2Perl can handle most data types. These are the basic constructs which are translated:

        "function xyz ( )" -> "sub xyz"
        "new Array(" -> "("
        "var xyz=" -> "$<pkg>::xyz=" --or-- "var xyz=" -> "my $xyz="
        "string + string..." -> "string.string..."  **but not translated in property lists
        "true" -> "1"
        "false" -> "0"
        "/.../" -> "'...'"
        ":" -> "=>" (in a property list)

These allowed constructs need no translation:

        []      array initializer -> array reference
        {}      object initializer -> hash reference
        =       assignment
        return  function return statement

The above set of constructs provides handling of most data types as Rvalues: boolean, string, number, array, pattern, or variable name.

The real beauty of this translator relies on the fact that the JavaScript object initializer is just like a Perl hash initializer. The key-value pairs are essentially the same. Thus, one may create useful data structures that translate easily.

Comments and Documentation

The JavaScript inline comment marker (//) is converted to the equivalent Perl marker (#).

The JavaScript block comment marker (/* ... */) is deleted; this allows you to have Javascript-only comments.

The Java doccomment marker (/** ... */) is treated specially, however. As with Java, the intent of this comment is external documentation. So this is handy for pod comments. The comment markers (/**) and (*/) are simply stripped leaving behind whatever was there. Make sure that the doccomment consists of a complete and correct pod section.

Restrictions

Arrays

You may use either the 'new Array()' or the '[]' array initializer, but the former has restrictions. Variable names are always translated as scalars, so an array assigned to a variable must be a reference using the '[]' initializer. In other uses (in a return statement, as a value for a property, etc.) either may be used.

Examples: This Rvalue translates without change to Perl.

        var myArray = [ 'abc', 'def', stringVar ];

Inside functions, the 'new Array()' construct may be used.

        return new Array('abc', 'def', stringVar );
The Plus Operator

The '+' operator in JavaScript is overloaded for arithmetic and concatenation. The concatenation function is assumed in assignment and return statements, favoring string operations. In property lists, though, where regular expressions have a higher chance of appearing-- and the '+' character would often appear -- the operator is not translated, hence it becomes arithmetic in Perl.

Functions

Only no-argument functions may be used. Again, the intent of this module is for a common data repository, so only very basic functions which just return data may be used.

Example

Input
        var lenVal = 5;
        var CCTypeList = ["visa", "mc", "amex", "diners", "jcb"];
        var s = "---" + name + "---";
        
        /**
        =head1 DESCRIPTION
        
        This is a sample doccomment which is both a valid JavaScript comment
        as well as being valid pod documentation once the doccomment markers
        are stripped off.
        (For purposes of this documentation this is indented; pod, of course,
        requires all pod commands to be flush-left.)
        
        =cut
        */
        function SysLib() {
                return new Array(
                        {       name:"Title",
                                required:true, // a comment here
                                pat:/^[a-zA-Z]{2,}$/,
                                patMsg:"must be at least 2 letters",
                                maxLen: lenVal,
                                enumList:CCTypeList
                        },
                        { . . .
                        },
                        . . .
                );
        }
Output
        my $lenVal = 5;
        my $CCTypeList = ["visa", "mc", "amex", "diners", "jcb"];
        my $s = "---" . name . "---";
        
        sub SysLib {
          return (
        
                { name => "Title",
                  required => 1, # a comment here
                  pat => '^[a-zA-Z]{2,}$',
                  patMsg => "must be at least 2 letters",
                  maxLen => $lenVal,
                  enumList => $Validate::Lib::CCTypeList
                },
                { . . .
                },
                . . .
                );
        }

CLASS VARIABLES

VERSION

Current version of this class.

CONSTRUCTOR

new

PACKAGE->new(pkgRoot, pkgName, fileSpec, packageVars)

Creates a SimpleJs2Perl object.

Parameters:

pkgRoot - string; path to perl library root

pkgName - string; package name for the generated perl file

fileSpec - string; name of javascript file

packageVars - optional; boolean; indicates to use package variables if true; lexical (my) variables if false

Returns:

a newly created object

METHODS

convertFile

OBJ->convertFile()

Converts the JavaScript file, returning a boolean status indicating success.

Returns:

boolean indicating whether conversion and loading was successful

POD ERRORS

Hey! The above document had some coding errors, which are explained below:

Around line 260:

=back doesn't take any parameters, but you said =back -- end of CLASS VARIABLES section

Around line 301:

=back doesn't take any parameters, but you said =back -- end of CONSTRUCTOR section

Around line 377:

=back doesn't take any parameters, but you said =back -- end of METHOD section


CleanCode Perl Libraries Copyright © 2001-2013 Michael Sorens - Revised 2013.06.30 Get CleanCode at SourceForge.net. Fast, secure and Free Open Source software downloads