You are unpacking a binary representation of a bunch of unsigned shorts ($hdr) into an array of perl scalars (@rgb), then replacing two elements in that array with packed unsigned shorts, which isn't what you want. Just substitute the new values directly into the array:

$rgb[16] = 7360; # Overwrite 3689 with 7360 $rgb[22] = 4912; # 2462 -> 4912

Now if you want to write this scalar array back to a binary file, try:

open(my $outfile, '>:raw', $hfn) or die "Couldn't open $hfn: $!\n"; # Overwrites existing file print $outfile pack("S*", @rgb); close($outfile) or die "Couldn't close $hfn: $!\n";

(The :raw modifier on the second argument of open is equivalent to using binmode).

If you know beforehand the positions and values in the binary file you need to change, you can save yourself the trouble of reading it all in to memory, unpacking everything to an array and re-packing it all at the end by just editing it in place:

open(my $fh, '+<:raw', $hfn) or die "Couldn't open $hfn: $!\n"; seek($fh, 2*16, 0); # Double up 'cause 'seek' wants bytes not short +ints print $fh pack('S', 7360); seek($fh, 2*22, 0); print $fh pack('S', 4912); close($fh) or die "Couldn't close $hfn: $!\n";

In reply to Re: Write 2 uint16_t numbers to file in Perl by Myrddin Wyllt
in thread Write 2 uint16_t numbers to file in Perl by BrianP

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.