linux poison RSS
linux poison Email

Perl Script: How to seek through the file

Perl provides two functions which enable you to skip forward or backward in a file so that you can skip or re-read data.

seek - moves backward or forward
tell - returns the distance in bytes, between the beginning of the file and the current position of the file

The syntax for the seek function is:
seek (file, distance, from)

As you can see, seek requires three arguments:

file: which is the file variable representing the file in which to skip
distance: which is an integer representing the number of bytes (characters) to skip
from:which is either 0, 1, or 2

-- 0 :  the number of bytes to skip from beginning of the file.
-- 1 :  the number of bytes to skip from current location of the file.
-- 2 :  the number of bytes to skip from end of the file.

Below is simple Perl script which demonstrate the usage of seek and tell.

Input: cat test.file
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 seek.pl
#!/usr/bin/perl

$FILE = "test.file";
open (INFILE, "$FILE") || die "Not able to open the file: $FILE \n";

while (1) {
        $skip = tell(INFILE);
        print "Starting with : $skip \n";
        $line = <INFILE>;
        print "$line";
        $skip = tell(INFILE);
        print "Ok, we now moved: $skip \n";
        print " ---------------------------------------- \n";

        seek (INFILE, "-".$skip, 1);
        $line = <INFILE>;
        print "$line";
        $skip = tell(INFILE);
        print "Ok, we now moved back to original: $skip \n";
        print " ---------------------------------------- \n";

        print "Now moving to eof \n";
        seek(INFILE, 0, 2);
        seek(INFILE,-80,1);
        $line = <INFILE>;
        print "$line";
        print " ---------------------------------------- \n";

        last;
}

Output: perl seek.pl
Starting with : 0
Perl defines three special subroutines that are executed at specific times.
Ok, we now moved: 76
 ----------------------------------------
Perl defines three special subroutines that are executed at specific times.
Ok, we now moved back to original: 76
 ----------------------------------------
Now moving to eof
le perl script which demonstrate the usage of these predefine perl subroutines.
 ----------------------------------------





0 comments:

Post a Comment

Related Posts with Thumbnails