Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: while behaviour on binary files

by ikegami (Pope)
on Nov 14, 2013 at 14:45 UTC ( #1062601=note: print w/ replies, xml ) Need Help??


in reply to while behaviour on binary files

while (!eof(DATFILE))

sub _read { my ($fh, $bytes_to_read) = @_; my $buf = ''; while ($bytes_to_read) { my $bytes_read = read($fh, $buf, $bytes_to_read, length($buf)); if (!$bytes_read) { die "Error reading: $!\n" if !defined($bytes_read); die "Unexpected EOF\n"; } $size -= $bytes_read; } return $buf; } sub read_uint32 { my ($fh) = @_; unpack('N', _read($fh, 4)) } #Or V? sub read_uint16 { my ($fh) = @_; unpack('n', _read($fh, 2)) } #Or v? sub read_pstring { my ($fh) = @_; _read($fh, read_uint16($fh)) } { open(my $fh, '<:raw', $datfilename) or die $!; read_uint32($fh); while (!eof($fh)) { my $profile_id = read_uint32($fh); my $seq1 = read_pstring($fh); my $seq2 = read_pstring($fh); read_uint16($fh); ... } }
Or if the "trailing zero" is meant to indicate the end of a list of sequences,
{ open(my $fh, '<:raw', $datfilename) or die $!; read_uint32($fh); while (!eof($fh)) { my $profile_id = read_uint32($fh); my @seqs; while (length( my $seq = read_pstring($fh) )) { push @seqs, $seq; } ... } }


Comment on Re: while behaviour on binary files
Select or Download Code
Replies are listed 'Best First'.
Re^2: while behaviour on binary files
by Anonymous Monk on Nov 14, 2013 at 15:26 UTC

    Thank you very much for your suggestions ikegami. The first one (!eof(DATFILE) solved my problem. I'll read up on while to understand why !eof changes the behaviour of while. After all I came here to seek wisdom and the journey to the solution often teaches you more than the solution itself. Thanks for pointing the direction I in which I have to travel. I'll also look into your other solutions and use that to make my code better. Sincerely, Hans

      Your misunderstanding is that <DATFILE> actually _reads_ from the file until the next end-of-line character. (You then throw away the data.) It's not the test for end-of-file. eof() is.
Re^2: while behaviour on binary files
by sundialsvc4 (Abbot) on Nov 14, 2013 at 15:15 UTC

    Nicely done.   ++ ...

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1062601]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (10)
As of 2015-09-03 12:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred temperature scale is:










    Results (109 votes), past polls