in reply to Converting Binary Numbers into Binary File

This deserves a one-liner:

perl -ne "$i++ || binmode(STDOUT);chomp;print pack(q/B*/,$_);" infile +>outfile

This is untested, but ought to work fine. It might be golfed down a bit if you allow it to set binmode on each iteration instead of only on the first iteration, and if you incorporate the -p switch instead of -n (which in this case, I believe hampers the legibility of the code):

perl -pe "binmode STDOUT;chomp;$_ = pack(q/B*/,$_);" infile >outfile

My biggest complaint with the golfed version is that it calls binmode on each iteration, which is unnecessary.


Dave

Replies are listed 'Best First'.
Re^2: Converting Binary Numbers into Binary File
by shmem (Chancellor) on Sep 13, 2006 at 16:56 UTC

    BEGIN block, then -

    perl -pe 'BEGIN{binmode STDOUT}$_=pack"B*",-+-$_'

    - 38 chars :-)

    <update>oops, wrong - that one strips leading zeroes.. oh, wait...

    perl -pe 'BEGIN{binmode STDOUT}chomp;$_=pack"B*",$_'
    </update>

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

      I'll beat your 41
      perl -pe 'BEGIN{binmode STDOUT}chomp;$_=pack"B*",$_'
      with 36
      perl -pe 'BEGIN{binmode STDOUT}$_=pack"B16",$_'

        15 for me ;-)
        perl -C0 -pe '$_=pack"B16",$_'
        Boris

        Take this:
        perl -e 'binmode STDOUT;print pack"(B16)*",<>'

        36, but without -p :-)

        _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                      /\_¯/(q    /
        ----------------------------  \__(m.====·.(_("always off the crowd"))."·
        ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}