mxb has asked for the wisdom of the Perl Monks concerning the following question:
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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Seeking with 'x' in unpack and out of bounds reads
by Eily (Monsignor) on Apr 27, 2018 at 10:30 UTC | |
by mxb (Pilgrim) on Apr 27, 2018 at 12:31 UTC | |
by Eily (Monsignor) on Apr 27, 2018 at 13:27 UTC | |
by vr (Curate) on Apr 27, 2018 at 15:36 UTC | |
by Eily (Monsignor) on Apr 27, 2018 at 15:56 UTC | |
by BillKSmith (Monsignor) on Apr 27, 2018 at 14:56 UTC | |
|
Re: Seeking with 'x' in unpack and out of bounds reads
by Anonymous Monk on Apr 27, 2018 at 16:26 UTC |