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

Perl interprets and executes source code every time (unless you use the Perl compiler).

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, 6.

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 organized at http://perldoc.perl.org/. Perl module documentation is embedded in the source code of every module, and can be accessed at predictable URLs (for example, http://search.cpan.org/perldoc?WWW::Mechanize), which always point at the latest version.

Java documentation is split into JDK™ 6 Documentation and Java™ Platform, Standard Edition 6 API Specification. Due to the naming confusion in Java versions, Google searches for Java documentation often return old versions of the documentation. For example, at the time of this writing, http://www.google.com/search?q=java+collection returns http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html as its second result, while the current documentation is http://java.sun.com/javase/6/docs/api/index.html?java/util/Collections.html. Note also that the older documentation has no link to the current version, nor is the URL scheme similar.

[edit] Libraries

All Perl modules are organized at http://search.cpan.org, a web portal featuring module versioning and diff; 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 there exists one for packages built with Maven: http://mvnrepository.com/. Maven Repository supports searching and tags but has no user ratings.

[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 does not support multiline strings. Variable interpolation is performed by the String.format() method.

[edit] Hashes

In Perl, hashes are defined very concisely:

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

In Java, there's no standard way to define hashes, or generally lists of key-value pairs. One could use a Map<String, String>, or a JavaBean-style object.

[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: impossible

[edit] I/O

  • Perl: the native I/O system is simple and easy to use. The IO::All module unifies I/O under a common interface.
  • Java: 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 doesn't automatically convert between strings and numbers (not even with explicit type casting):

String s = (String) 42

will produce an error:

inconvertible types
found   : int
required: java.lang.String

Integer.parseInt and Integer.getInteger convert a string to, respectively, integer primitive and its wrapper object.

[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: the operation is complex enough that it warrants its own Stack Overflow question:

In Java how do a read an input stream in to a string?

Boy, I'm absolutely in love with Java, but this question comes up so often you'd think they'd just figure out that the chaining of streams is somewhat difficult and either make helpers to create various combinations or rethink the whole thing.

Bill K, 9,151 Stack Overflow reputation points

[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

Perl Myths 200909 is a presentation by Tim Bunce that dispels the myths that Perl would be dead, hard to read/test/maintain, or that Perl 5 is killed by Perl 6. The last slide reads:

                  Perl
 
has a massive library of reusable code
has a culture of best practice and testing
has a happy welcoming growing community
has a great future in Perl 5 and Perl 6
is a great language for getting your job done
    for the last 20 years, and the next 20!

Opera Software also published a presentation at YAPC::EU::2009 - How Opera Software uses Perl, which starting at slide 12, addresses common misconceptions about 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 very large websites (IMDB, Magazines.com, BBC, Amazon.com, LiveJournal, Ticketmaster, Craigslist, [3], etc.).

[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
Related Ads