Archive for August, 2009

Reading in a file with Perl and Java

This is why people love Perl. A small amount of work to do a BIG TASK:

        $file_name = "somefile.txt";
        open (my $fh, $file_name) or die "Ouch: $!\n";
        # $text variable now contains whatever the file contains
        $text = do {
            local $/ = undef;
            <$fh>;
        };
        close($fh) or die("Ugh: $!\n");

Just to compare, this is how you would do in Java:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class ReadFile {
    public static void main (String[] args) {
        try {
            String filename = "somefile.txt";
            BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
            ArrayList lines = new ArrayList();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                lines.add(line);
            }
            bufferedReader.close();
        }
        catch (IOException e) {
              System.err.println("OUCH!!!!");
        }
    }
}

After this, you get a list of string that contains contents of a file. This is a little extreme case, but still… it shows how much of work you would do if you want to do the same job in Java.

Python Decorator Revisited, Part 1: What is a decorator?

I love programming in Python. It not only keeps lines of code to the minimum but also has great language features that allow developers to think about programming in different ways. I often get confused whether Python is a object-oriented language or a funcitonal programming language (to clarify, it is a general-purpose programming language). It even has lambda functions!! However, the one language feature that I like the most is decorator. Decorator is simply a syntatic sugar that looks like Java’s annotation. This is a simple example of decorator in Python:

@decorator
def decorated_func():
... some code ...

Same as . . .

def decorated_func():
... some code ...

decorated_func = decorator(decorated
_func)

Basically, decorator is a function that can do anything before and after a decorated_func gets called. This is closely related to the decorator design pattern, which dynamically add functionality or responsibility to an existing object. With that said, you can add as many decorators as you can as long as their types are matched:

@decorator1
@decorator2
@decorator3
def decorated_func():
     ... some code ....

In the next two posts, I will go over how to create a decorator for general functions and classes. I will also go over some interesting ways of using decorators, such as the famous memoized decorator.