tags:

views:

31

answers:

2

I'm trying to use getpos in Perl. I am using a FileHandle object in the code below, and it doesn't seem to be working. Can anyone tell me what I'm doing wrong?

use strict;
use warnings;
use FileHandle;

my $fh = new FileHandle;
$fh->open("<test.txt") or die "$!";
my $pos = $fh->getpos;
print "pos: \"$pos\"\n";

The output is:

pos: ""

I would expect "0" to be output...

+4  A: 

The documentation for FileHandle says that the value returned by getpos is an opaque value which means that in general you cannot assume anything meaningful about the value. The only thing it's good for is passing back to setpos. This matches the underlying system calls used to implement the method (fgetpos and fsetpos) which are represented in C as opaque fpos_t pointers. The seek and tell methods if available use integer file positions that can be manipulated.

Geoff Reedy
+4  A: 

Note the caveat (emphasis added) in the documentation:

If the C functions fgetpos and fsetpos are available, then FileHandle::getpos returns an opaque value that represents the current position of the FileHandle, and FileHandle::setpos uses that value to return to a previously visited position.

Opaque means you shouldn't pay attention the value: use it only as a parameter in future requests from the module.

Why not use Perl's tell and seek operators?

#! /usr/bin/perl

use warnings;
use strict;

open my $fh, "<", $0 or die "$0: open: $!";
print tell($fh), "\n";

The output of the above program is 0, as you expect.

Greg Bacon