Perl vs Java

From WikiVS, the open comparison website
Jump to: navigation, search
Perl Java
Perl
VS
Java
http://www.perl.org http://java.sun.com

Contents

[edit] Philosophy

[...] Perl doesn't have an infatuation with enforced privacy. It would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun.

Larry Wall

[edit] Program execution

Every time that you run perl, in rough terms, it compiles the source code into the bytecode and then starts executing the bytecode. Although technically the process is more complicated than this as, for example, BEGIN blocks pause compilation and are executed immediately, whereas loading a new module, or calling an 'eval' block during execution will start a new phase of compilation. It's normal in modern web environments to use some method of persisting the perl interpreter, to avoid re-compiling entirely from scratch.

javac compiles programs into bytecode, then java runs the bytecode in the Java virtual machine.

[edit] Versions

Perl uses a simple naming and versioning scheme: Perl 4, 5_005, 5.6, 5.8, 5.10, 5.12, 5.14, 5.16, 5.18. (Perl 6 being a language in the Perl family, but not a replacement for Perl 5.)

Java 1.5.0 became Java 5, Java 1.6.0 became 6. Java 6 dropped the j2se name and is now just javase.

[edit] Documentation

Perl documentation is usually installed with the interpreter and available by using the perldoc command, a web mirror of the documentation for all perl releases since 5.8.8 is available at http://perldoc.perl.org/. Perl module documentation is embedded in the source code of every module in POD format, and can likewise be accessed locally using the perldoc command (for installed modules). There are web interfaces to the CPAN (centralized repository of perl modules), which allow you to search for modules and read the documentation for any module - eg https://metacpan.org/ and http://search.cpan.org/ .

All standard Java is documented using javadoc, a tool for dynamically creating html documentation of java API's using code comments. All JDK's (Java development kits) include the complete java source and in turn will include the complete javadoc documentation for all of the Java api's. Most popular IDEs include support for bringing up the complete documentation for any java function. By pressing the f2 key in eclipse, or Ctr-Shift-Space in netbeans, developers can quickly and simply bring up the documentation for any function selected by the cursor. For users searching for functions, developers can quickly and easily bring up lists of all defined functions with their complete documentation for any object by using the auto-complete function (ctrl-space in eclipse and net beans). Documentation for the java standard libraries is also online in dynamically created javadoc repositories hosted by oracle, but this is discouraged by experienced users since using the local documentation can prevent confusion about which version of java's documentation the users is looking at and using the local copies is easier and faster.

[edit] Libraries

All Perl modules are organized via the CPAN, which is mirrored around the globe. All uploads into the CPAN are automatically tested across a wide range of architectures and operating systems via the CPAN testers group. Web portals into the CPAN exist at https://metacpan.org/ and http://search.cpan.org . These portals feature version and diff browsing; integrated documentation search and display; user reviews and ratings of modules (documentation, interface, ease of use, overall); bug reporting; source code download; discussion forum; test results across a variety of platforms; and links to external web sites or bug tracking systems.

Java does not have a single recognized repository for reusable code, but instead has multiple sources for standardized java extensions. Popular repositories for open source java code include the apache foundation, the maven repositories, or the community driven javaforge.com.

[edit] Data Structures

[edit] Strings

Perl supports multiline strings, by simply inserting line breaks in the string, or by using the HERE-DOC syntax. Perl also supports scalar, array and hash element interpolation in strings delimited by double quotes.

Java supports multiline strings by using the "\n" escape code to indicate a line break and the + operator to break a long string constant into pieces on successive lines. Variable interpolation is performed by the String.format() method.

[edit] Hashes

Perl

In Perl, hashes are defined very concisely:

my %person = (
    name => 'John',
    age => 29
);

Java

In Java, there's no standard way to define hashes, or generally lists of key-value pairs. Java includes the interface Map, which defines all of the functions needed to efficiently work with maps in java. Java then provides multiple implementations of map, allowing the user to choose the implementation which is most performant given the needs of the calling application. These implementations include, hashMap, treeMap and linkedListMap. Maps in java are generic, meaning that the data type expected by the maps can be chosen at compile time by the programmer. The java hashMap,

 new HashMap<String, Object>()

should provide the same functionality as the perl hash except with the added caveat that objects retrieved from the map must be casted before all of the functionality of the retrieved object may be used. Unlike perl, keys in java hashes do not need to be strings. The hash map

 new HashMap<Object, Object>()

is able to map any object to any other object based upon hash values produced by the Object#hashValue() function. Java also provides many hash based data structures not provided by perl. These include HashTable (a synchronized hashMap) and HashSet.

[edit] Regular expressions

Executing code in the replacement part of a regular expression search and replace:

Perl: s/The temperature is (\d+)C/'The temperature is' . celsius2Fahrenheit($1) . 'F')/e

Java: Regex support is added via classes in the core java library.

StringBuffer sb = new StringBuffer();
Matcher m = Pattern.compile("The temperature is \\d+C").matcher(s);
while (m.find()) {
	Matcher m2 = Pattern.compile("\\d+").matcher(m.group(0));
	m2.find();
	m.appendReplacement(sb, "The temperature is " + convertToFarenheight(m2.group(0)) + "C");
}
s = m.appendTail(sb).toString();

[edit] I/O

  • Perl: the native I/O system is designed to be simple and easy to use. The IO::All module unifies I/O under a common interface.
  • Java: Native I/O system is also simple and easy to use for simple tasks. The java.io package unifies I/O under a common interface. Due to the robustness, it can become quite complex for heavier tasks such as with message passing or asynchronous I/O. Bruce Eckel admits the Java I/O is complex:

[...] there are so many classes for Java's I/O system that it can be intimidating at first

Bruce Eckel, Thinking in Java, 4th edition, p.901

The reason that the Java I/O library is awkward to use is that you must create many classes --the "core" I/O type plus all the decorators-- in order to get the single I/O object that you want.

Bruce Eckel, Thinking in Java, 4th edition, p.919

[edit] Gotchas

[edit] Java

A gotcha is a nasty surprise in the Java language or the standard libraries. Some might call them bugs, some features. Sometimes they are the result of incompetence or carelessness on the part of the language designers and sometimes they are just quirky things that cannot be helped.

Roedy Green, Canadian Mind Products

An extensive list of Java gotchas can be found at http://mindprod.com/jgloss/gotchas.html. OOP-related Java gotchas can be found at http://www.firstsql.com/java/gotchas/.

[edit] String equality

Some programmers may test for string equality using the == operator. However, this actually tests that two objects are the same, and the comparison will be misleadingly successful if no strings are created via the new operator. The correct way to test for string equality in Java is to use the .equals() method.[1]

[edit] Conversions between strings and numbers

Java automatically converts between strings and numbers when a number is preceded by a string:

String s = "" + 42 + 3

will produce a string:

423

Whereas

String s = 42 + 3;

will generate an error.

Integer.parseInt converts a string to integer, it should not be confused with Integer.getInteger(String) which retrieves the value of an environment variable.

[edit] Perl

Strings can be autoincremented ($a = 'abc'; $a++' # $a is 'abd' now), but not autodecremented ($a-- will produce -1). Java doesn't have string increment/decrement at all natively.

Sigils allow the same variable name to refer to a scalar, an array, a hash, a file handle etc. $foo and @foo are totally different variables. However, other languages don't even have the concept, so don't do it in Perl either.

See more gotchas at Perl gotchas.

[edit] Common operations

For basic operations, Java is generally more verbose than Perl.

[edit] Reading a string

  • Perl: my $string = <> will read a line from the standard input. my $string = <$file> will read a line from a previously opened file. A prior undef $/ statement will cause reading of the entire input instead (something that cannot be done in one Java statement).
  • Java: Apache's IOUtils has a simple method to copy from one input stream to another, with a String output stream being used to write to a string.
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

(Stack Overflow question)

[edit] HTTP POST request

Perl code:

use HTTP::Request::Common 'POST';
use LWP::UserAgent;
 
my $ua = LWP::UserAgent->new;
 
my $request = POST 'http://example.com/login',
    [ username => 'john',
      password => 'secret',
    ];
 
my $response = $ua->request($request);
 
die "Couldn't POST" if not $res->is_success;
 
print $res->content;

Java code, using the de-facto HTTP library Apache HttpComponents Client:

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
 
public class HttpPost {
    public static void main(String[] Args) {
 
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://example.com/login");
 
        // this is how you set the body of the POST request (!)
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", "john"));
        params.add(new BasicNameValuePair("password", "secret"));
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
 
        String responseBody = "";
        try {
            // Create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            responseBody = httpclient.execute(httppost, responseHandler);
        } catch(HttpResponseException e) {
            String error = "unknown error";
            if (e.getStatusCode() == 400) {
                // responseBody is null here, even though packet sniffing reveals a response such as:
                // Transfer-Encoding: chunked
                // Content-Type: application/json
                //
                // 56
                // {"error": "You do not have permissions to login."}
            }
            throw new Exception("Error while retrieving " + httppost.getURI() + ": "
                + e.getStatusCode() + " " + e.getMessage() + " (" + error + ")");
        }
 
        httpclient.getConnectionManager().shutdown();
    }
}


[edit] Web application development

Perl's flagship web application framework is Catalyst.

Java has numerous competing web application frameworks, of which 57 alone are open-sourced.

Well, what Java web framework should I use?

shrug, beats me.

Tim O'Brien, O'Reilly ONJava.com

[edit] Common criticisms

[edit] Perl

[edit] Perl is line noise, or write-only

Perl can indeed look like line noise, and Perl enthusiasts compete in writing the shortest program that will achieve a simple task (see Perl Golfing or the Obfuscated Perl Contest). Also popular are Just Another Perl Hacker signatures - Perl programs that print the string "Just another Perl hacker", but look nothing like it:

not exp log srand xor s qq qx xor
s x x length uc ord and print chr
ord for qw q join use sub tied qx
xor eval xor print qq q q xor int
eval lc q m cos and print chr ord
for qw y abs ne open tied hex exp
ref y m xor scalar srand print qq
q q xor int eval lc qq y sqrt cos
and print chr ord for qw x printf
each return local x y or print qq
s s and eval q s undef or oct xor
time xor ref print chr int ord lc
foreach qw y hex alarm chdir kill
exec return y s gt sin sort split

However, Perl can be used to write very clean, concise and expressive code. For example, to print the lines in a file sorted in reverse order:

open my $file, '<', "filename.txt";
print reverse sort <$file>;

For OOP, Moose provides elegance in class definition and extension, method overriding (notice the use of the after modifier to transparently call the inherited method first) and so on:

package Point;
use Moose;
 
has 'x' => (isa => 'Int', is => 'rw', required => 1);
has 'y' => (isa => 'Int', is => 'rw', required => 1);
 
sub clear {
    my $self = shift;
    $self->x(0);
    $self->y(0);
}
 
package Point3D;
use Moose;
 
extends 'Point';
 
has 'z' => (isa => 'Int', is => 'rw', required => 1);
 
after 'clear' => sub {
    my $self = shift;
    $self->z(0);
};


[edit] Perl is mostly for scripting

While that has been the case in the '90s, Perl is nowadays used for a variety of tasks, including complex desktop applications such as the Perl IDE (screenshots), web application frameworks (Catalyst), bioinformatics (extensively)[2], content management systems (e.g. WebGUI), hierarchical wikis (MojoMojo) etc. and powers the backends of very large websites (IMDB, Magazines.com, BBC, Amazon.com, LiveJournal, Ticketmaster, Craigslist, [3], etc.) although many of the aformentioned sites have front end webservers written in either java, ruby, or on the .NET framework.

[edit] Humor

[edit] Perl

If you put a million monkeys at a million keyboards, one of them will eventually write a Java program.
The rest of them will write Perl programs.

Go -f>@+?*<.-&'_:$#/%! yourself! – Schwern

@Schwern: Looking at that (particularly the way it starts with -f) I thought "No, it can't be..."
... but it is. Valid Perl. Now what am I supposed to say next time they make fun of us? :( – Adam Bellaire


[edit] Java

“Knock, knock.”

“Who’s there?”

…very long pause…

“Java.”

--

"If Java had true garbage collection, most programs would delete themselves upon execution." -- Robert Sewell

--

"Saying Java is better because it works on all platforms is like saying anal sex is better because it works on both genders".

[edit] Links

[edit] Against Java

  • Wikipedia - Criticism of Java
  • Java Sucks - Rant by Jamie Zawinski, with many detailed criticisms of the Java language itself and its supporting libraries.
  • A critique of Java - Harold Thimbleby discusses why Java itself as a programming language leaves much to be desired and highlights a few serious problems with Java's design.

See Also the Following Articles

Personal tools
Namespaces
Variants
Actions
Navigation
Ads
Toolbox