0

I want to read a text file data.txt using read. I would like to read the first four integers of each line at a time.

data.txt

line1 0101020102
line2 2010201001
line3 0201010201

The line1 etc. are part of the file.

This is what I could do up to now

Perl

my $data;
my $IN;
my $n = 0;

$line = 1;

open($IN, '<', "data.txt") or die " Error";

while ( $line != 0 ) {
    seek($IN, 6, SEEK_SET);
    $line = read($IN, $data, 4);
    seek($IN, 0, SEEK_SET);
}

The problem is that using this while loop, Perl keeps reading the first line in an infinite loop.

How can I deal with this problem?

2
  • 2
    Why would it do anything else, when you seek() to the beginning of the file after every read? Commented Sep 1, 2018 at 15:15
  • Are you thinking that using read is a good idea here (it isn't) or are you simply experimenting with the operator? Commented Sep 1, 2018 at 20:52

1 Answer 1

2

I think you misunderstand what seek() does. With SEEK_SET as the third parameter, the second parameter is interpreted as the position to move to as measured from the start of the file. So every time you run this line:

seek($IN, 6, SEEK_SET);

It always moves to the seventh position in the file (which is, obviously, always on the same line). Then when you run this line:

seek($IN, 0, SEEK_SET);

It always moves back to the start of the file.

Initially, I thought the solution was to change SEEK_SET to SEEK_CUR (which interprets the second parameter as the amount to move relative to the current position) but it's a bit more complex than that. Here's how I got it to work:

seek($IN, 6, SEEK_CUR); # Move forward six spaces
$line = read($IN, $data, 4);
seek($IN, 7, SEEK_CUR); # Move forward seven places

But really, a regex is the best approach here.

while(<$IN>) {
    ($data) = /\s(\d{4})/;
    print "$data\n";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this won't work on Windows, because you assume a single additional line terminator character whereas Windows uses two

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.