Thursday, March 17, 2011

Perl: BEGIN and END


Perl ScriptOutput
BEGIN {
    print "Birth of a process...\n";
}

print "Life of a process...\n";
die "Murder of a process...\n";

END {
    print "Death of a process...\n";
}
Birth of a process...
Life of a process...
Murder of a process...
Death of a process...
bash-2.03$ 
bash-2.03$ 
 
Perl ScriptOutput
BEGIN {
    print "Birth still runs !\n";
}

This won't compile;

END {
    print "Death still runs !\n";
}

Birth still runs !
Can't locate object method "This" via package "won::t"
(perhaps you forgot to load "won::t"?) at 1.pl line 5.
Death still runs !

 
Perl ScriptOutput
die "Bye";

END   { print "End 1\n"    }
BEGIN { print "Begin 1\n"; }
END   { print "End 2\n"    }
BEGIN { print "Begin 2\n"; }

Begin 1
Begin 2
Bye at 1.pl line 1.
End 2
End 1

BEGIN

Run some code as soon as it has all been read in by the parser and before the rest compiles.

END

Run some code as late as possible. When the interpreter is ready to shut down.

Monday, March 14, 2011

How to implement callback functions in Java?


The callback function is excutable code that is called through a function pointer. You pass a callback function pointer as an argument to other code, or register callback function pointer in somewhere. When something happens, the callback function is invoked.
C/C++ allow function pointers as arguments to other functions but there are no pointers in Java. In Java, only objects and primitive data types can be passed to methods of a class. Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks. You should declare an interface which declares the function you want to pass.
The collections.sort(List list, Comparator c) is an example of implementing callback function in Java. The c is an instance of a class which implements compare(e1, e2)method in the Comparator interface. It sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator.
Use inner classes to define an anonymous callback class, instantiate an anonymous callback delegate object, and pass it as a parameter all in one line. One of the common usage for inner classes is to implement interfaces in event handling.
class SomePanel extends JPanel {

    private JButton    myGreetingButton = new JButton("Hello");
    private JTextField myGreetingField  = new JTextField(20);

    private ActionListener doGreeting = new ActionListener {
            public void actionPerformed(ActionEvent e) {
               myGreetingField.setText("Hello");
            }
 };

    public SomePanel() {
        myGreetingButton.addActionListener(doGreeting);
        // . . . Layout the panel.
    }

}
Source: http://www.xyzws.com/javafaq/how-to-implement-callback-functions-in-java/157