Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Unpack Bin file problem

by mark4444az (Sexton)
on Mar 01, 2013 at 21:26 UTC ( #1021346=perlquestion: print w/ replies, xml ) Need Help??
mark4444az has asked for the wisdom of the Perl Monks concerning the following question:

I'm novice level and in a little over my head on this one. I have some code (run from cygwin)where I unpack a bin file to a text file:
open (OUTFILE, ">bin.txt") or die "Can't open new text file! \n" , &cl +ean_up; # Make temp text file to unpack the bin file open (INFILE, "$bin_file_name") or die "Can't open nvm file! \n" , + &clean_up; # Open nvm binary file #### This unpacks the binary file and puts it in a text file bin.t +xt #### my @lines = unpack ("W*", <INFILE>); my $line; foreach $line (@lines) { print OUTFILE sprintf("%02X", $line); } close (OUTFILE); close (INFILE);
The &clean_up sub just removes files and that works fine. The problem I have is when I unpacked a bin file it stopped printing on 0x0A, which is an ascii line feed. I changed it to an 0x0B and it worked fine. This makes me think that my printout is content sensitive, which would be BAD. I further suspect that the W* may be the wrong way to go on this. Any suggestions?

Comment on Unpack Bin file problem
Download Code
Re: Unpack Bin file problem
by bart (Canon) on Mar 01, 2013 at 21:38 UTC
    Your problem is in
    my @lines = unpack ("W*", <INFILE>);
    and you haven't touched $/, so this will just read one line, until the first "\n".


    local $/;
    just before you read the file, for example in a bare block, and oh, don't forget to binmode the filehandle if this has to work on something other than Linux, and it'll work fine. It sets this special variable to undef, in case you were wondering, so now you'll read the whole file.
      OK, That worked. Your comment, "It sets the special variable to undef", is not yet clear to me. I will have to research this. I greatly appreciate you help. I understand the concept of $_, just not how local $/ modifies it.
        It doesn't modify the behavior of $_, but of <INFILE> (for any handle).

        Perl has a bunch of special variables that change the behavior of perl. $/ Is one of them, it changes what string readline, and thus <INFILE>, searches for as a line terminator, to read a whole line at once. When undef, it'll just make it slurp in the rest of the file.

        OK, that makes sense now. Thanks again.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1021346]
Approved by bart
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2014-07-25 01:48 GMT
Find Nodes?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:

    Results (167 votes), past polls