Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Writing the elements of an array to a file

by choroba (Cardinal)
on Aug 31, 2015 at 15:20 UTC ( [id://1140545]=note: print w/replies, xml ) Need Help??


in reply to Writing the elements of an array to a file

The shortest and most effective way is to use a quantifier in pack:
print {$FILE} pack 'C4', @arr;

You should have thought of a loop at least:

print {$FILE} pack 'C', $_ for @arr;

Update: If you need pack, the array doesn't contain binary data. It contains the numbers.

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

Replies are listed 'Best First'.
Re^2: Writing the elements of an array to a file
by bontchev (Sexton) on Aug 31, 2015 at 15:46 UTC

    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.

      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,

      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:  <%-{-{-{-<

      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.

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1140545]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (7)
As of 2024-04-19 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found