editi has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
Monks i try to writy a file as a binary
the file should contains a binary values corresponding to character values
i tried the following code
but it is not working
please help me
#!/usr/bin/perl open FILE, ">123.txt" or die $!; print pack("b*","a","b","c") or die $!; close FILE;
thanks in advance.

Replies are listed 'Best First'.
Re: Write a File in Binary?
by Adrade (Pilgrim) on Jul 03, 2007 at 17:27 UTC
    Hi editi,

    First, you're not writing to the file... reformat the third line to read print FILE pack("b*","a","b","c") or die $!;

    Additionally, you'll want, after you open FILE, to write binmode(FILE); - I dont know if this is necessary on all platforms, but it certainly can't hurt.

    Best of luck,
    -Adam

    --
    By a scallop's forelocks!

Re: Write a File in Binary?
by kyle (Abbot) on Jul 03, 2007 at 17:31 UTC

    It might help to use binmode.

    Your print needs to specify what filehandle it's going to print to (print FILE pack("b*","a","b","c")).

    If you want to write the bits for the characters, I think print FILE "a","b","c" would work just fine, unless I'm missing something. In any case, I think you should have a look at the pack documentation. I don't think "b*" is the format you want (but I can't tell what format you do want).

Re: Write a File in Binary?
by marto (Cardinal) on Jul 03, 2007 at 17:33 UTC
Re: Write a File in Binary?
by Limbic~Region (Chancellor) on Jul 03, 2007 at 17:28 UTC
    editi,
    Since you didn't bother to tell us what didn't work, I can't tell you what's wrong. I can point you to binmode and print as well as suggest you provide more information.

    Update: Ok, so after posting I realized I was not being very nice nor was I being as helpful as I could be. I was trying to stress how useless "it didn't work" is when asking a question. While I did point to the docs that ultimately would have lead to the answer, Adrade was much kinder and informative.

    Cheers - L~R