perl function seek

‮h‬ttps://www.theitroad.com

The seek function in Perl is used to reposition the file pointer to a specified position within a file. It is typically used when reading or writing files.

Here's an example of using seek to move the file pointer to a specific position in a file:

open FILE, "<", "example.txt" or die $!;
seek FILE, 10, 0; # move the file pointer to position 10
my $line = <FILE>; # read the next line from the file
print "$line\n"; # print the line starting at position 10
close FILE;

In this example, the open function is used to open the file "example.txt" for reading. The seek function is then used to move the file pointer to position 10, which is 10 bytes from the beginning of the file (0). The <> operator is used to read the next line from the file, starting at the current file position. The result is assigned to the variable $line, which is then printed.

Note that the second argument to seek is the offset from the specified position, which can be positive or negative. For example, to move the file pointer to the end of the file, you can use a negative offset:

open FILE, "<", "example.txt" or die $!;
seek FILE, -5, 2; # move the file pointer 5 bytes before the end of the file
my $line = <FILE>; # read the next line from the file
print "$line\n"; # print the last line in the file
close FILE;

In this example, the seek function is used to move the file pointer 5 bytes before the end of the file (2), which is equivalent to moving the file pointer to the end of the file minus 5 bytes. The <> operator is used to read the next line from the file, which is the last line in the file. The result is assigned to the variable $line, which is then printed.