CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Binary Files...

 



yapp
User

Aug 29, 2001, 3:43 AM

Post #1 of 5 (1079 views)
Binary Files... Can't Post

Hi There.

I've got a prop with making binary-type-files in perl. Normally I use text files to save my data, but this time Iwant to try using a binary structure (using pack and unpack?) Who knows howto make that?
I hope it's possible to make something like first byte=number, then variable length string, etc.





mhx
Enthusiast / Moderator

Aug 29, 2001, 4:36 AM

Post #2 of 5 (1075 views)
Re: Binary Files... [In reply to] Can't Post

First, you need to be sure your file handle is set to binary mode. See perldoc -f binmode for details on this.
Second, the functions you're searching for are pack and unpack. You will find detailed information on these functions with perldoc -f pack and perldoc -f unpack.
Hope this helps.

-- Marcus


Code
s$$ab21b8d15c3d97bd6317286d$;$"=547269736;split'i',join$,,map{chr(($*+= 
($">>=1)&1?-hex:hex)+0140)}/./g;$"=chr$";s;.;\u$&;for@_[0,2];print"@_,"



yapp
User

Aug 30, 2001, 5:30 AM

Post #3 of 5 (1067 views)
Re: Binary Files... [In reply to] Can't Post

That you for your advice, but unfortunatuly I already knew that. I read thu the perldoc. I need binmode() on some systems, but I don't get pack() and unpack()!

What kind of template/formula should I use when I want to save a number, variable length string, numbers and so on? Especially the variable length is the proplem.

Anyway, who userstands such things?



mhx
Enthusiast / Moderator

Aug 30, 2001, 9:52 AM

Post #4 of 5 (1065 views)
Re: Binary Files... [In reply to] Can't Post

Say you've got two strings $s1 and $s2, then you can use for example:

Code
#!/bin/perl -w 
use strict;

my $s1 = 'foo bar';
my $s2 = 'Hello World';

my $bin = pack 'na*na*', length $s1, $s1,
length $s2, $s2;

# now do something with $bin

my($u1,$u2) = unpack 'n/an/a', $bin;

print "[$u1]\n[$u2]\n";

This will work for strings of up to 65535 characters. 'n' is always a big endian unsigned 2-byte integer.
Hope this helps.

-- Marcus


Code
s$$ab21b8d15c3d97bd6317286d$;$"=547269736;split'i',join$,,map{chr(($*+= 
($">>=1)&1?-hex:hex)+0140)}/./g;$"=chr$";s;.;\u$&;for@_[0,2];print"@_,"



yapp
User

Sep 4, 2001, 2:23 AM

Post #5 of 5 (1054 views)
Re: Binary Files... [In reply to] Can't Post

That leaves me still with one question. I hope someone can answer it. How do I store 100 strings efficiently in a file?


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives