Helloworld
Helloworld

Reputation: 43

Seek function not working in perl

I tried the below code snippet and the seek function doesn't seem to work.

funct("ls -ltr /scratch/dummy/dum*");

sub funct {

print "\nRecording\n";
open(SENSOR_LIST1, "$_[0] |") || die "Failed to read sensor list: $!\n";
for $sensor_line1 (<SENSOR_LIST1>) {
   print "$sensor_line1";
}
my $pos = tell SENSOR_LIST1;
print "\nposition is $pos"; #Here the position is 613

print "\nRecording again";
seek (SENSOR_LIST1, SEEK_SET, 0);
$pos = tell SENSOR_LIST1; # Here again the position is 613, even after a seek
print "\nposition now is $pos";

for $sensor_line1 (<SENSOR_LIST1>) {
        print "$sensor_line1";
    }
close SENSOR_LIST1;
}

Note: All variants of seek doesn't work.

Output:

The position does not change even after the seek. It remains in 613.

Can you guys, check and let me know what is the issue here?

Thanks.

Upvotes: 3

Views: 362

Answers (2)

Dave Sherohman
Dave Sherohman

Reputation: 46187

Try writing the output of your ls command to a file and opening that file instead of reading the command's output directly. You can't seek on a transient data stream (such as a command's output), only on data which still exists after being read (such as a file).

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60007

You cannot seek on a pipe.

Either use a temporary file or store the data in memory.

Your choice as to the best solution

Upvotes: 6

Related Questions