Thursday, October 11, 2012
10:00 PM

Perl Script: Predefine Perl subroutine (BEGIN, END and AUTOLOAD)


Perl defines three special subroutines that are executed at specific times.

 * The BEGIN subroutine, which is called when your program starts.
 * The END subroutine, which is called when your program terminates.
 * The AUTOLOAD subroutine, which is called when your program can't find a subroutine to executed.

Below is simple perl script which demonstrate the usage of these predefine perl subroutines.

Source: cat predefine_fun.pl
#!/usr/bin/perl

# This will get executed first when your program is started.
BEGIN {
        print "Starting the loop ... \n";
        print " ------------------------- \n";
}

# This will get executed when your program terminates.
END {
        print " ------------------------- \n";
        print "End of this perl script \n";
        print "Perl is awesome :) \n";
}

# This is called whenever the Perl try to call a subroutine that does not exist.
AUTOLOAD {
        print "Oosp, we are not able to find the required function : $AUTOLOAD \n";
        print "This is bad \n"
}

for ($i = 0; $i < 5 ;$i++ ) {
        print "$i \n";
}

&doesnotexists;


Continue Reading...

0 comments:

Post a Comment