Hi Monks

I'm a little confused regarding seeking with the x command with unpack.

This came about in this node in my thread yesterday.

In a format such as PNG, where the first field to extract is not at the start of the packed format, you seek with x before extracting. However, when the string to be unpacked is 'too short' in that it doesn't have enough bytes to seek with 'x', Perl will die rather than safely stop parsing.

I have reduced this down to the following test-case. Is this expected behaviour with x or am I attempting to approach the problem incorrectly?

Many thanks.

#!/usr/bin/env perl use strict; use warnings; use 5.016; my $str = "\x00\x00\x01\x00\x00\x02"; my @vals; # This works - exact multiple of 'x2C' say "length:", length($str); @vals = unpack "(x2C)*", $str; say join "\n", @vals; $str .= "\x00"; # This works - not a multiple of 'SC' say "length:", length($str); @vals = unpack "(SC)*", $str; say join "\n", @vals; # This fails - not a multiple of 'x2C' say "length:", length($str); @vals = unpack "(x2C)*", $str; # ^-- dies here with: 'x' outside of string in unpack say join "\n", @vals;

In reply to Seeking with 'x' in unpack and out of bounds reads by mxb

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.