in reply to Re: Writing the elements of an array to a file
in thread Writing the elements of an array to a file

Thanks!

Using a quantifier did the trick; I didn't know that using pack() this way was possible.

The documentation suggests that the quantifier should be surrounded by square brackets, as in pack ("C[4]", @arr)? I guess it doesn't matter.

Not sure I understand your remark about the binary data. The elements are the result of some bit-wise operations on data. Perl keeps them in its internal representation of numbers; I just want them output as binary data (bytes). If I don't use pack(), Perl just outputs them as it would output any number by default - as a decimal number in ASCII format, which isn't what I want.

Replies are listed 'Best First'.
Re^3: Writing the elements of an array to a file
by Athanasius (Archbishop) on Aug 31, 2015 at 15:56 UTC

    Hello bontchev,

    The documentation suggests that the quantifier should be surrounded by square brackets...

    Not really. From pack (emphasis added):

    The following rules apply:
    • Each letter may optionally be followed by a number indicating the repeat count. A numeric repeat count may optionally be enclosed in brackets, ...

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re^3: Writing the elements of an array to a file
by AnomalousMonk (Archbishop) on Aug 31, 2015 at 17:22 UTC

    It's also possible to use  '*' as a quantifier to pack/unpack whatever number of the specified data type happens to be present:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my $p = pack 'C*', (65, 66, 0x43, ord('D'), 0b01000101); print qq{'$p'}; ;; my @u = unpack 'C*', $p; dd \@u; " 'ABCDE' [65 .. 69]


    Give a man a fish:  <%-{-{-{-<

Re^3: Writing the elements of an array to a file
by choroba (Cardinal) on Aug 31, 2015 at 15:55 UTC
    Binary data versus numbers:
    print "\x45" | "\x59"; # Prints \x5d. print 'E' | 'Y'; # Same as the above, prints ]. print 69 | 89; # Prints 93 (5d in hex).

    | is clever, it knows whether it operates on bytes (strings) or numbers.

    Update: fixed typo (s/78/89/), thanks poj.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ