Search code examples
perlpackunpack

Unpack uneven amount of bytes with Perl


Is there a way to force unpack to treat a single byte as a “null padded” short, while unpacking a scalar with an uneven amount of bytes?

Example code:

my $input = 'abcde';
foreach (unpack 'S*', $input) {
    print "$_ ";
}

# Result:
# 25185 25699

# Expected result:
# 25185 25699 101

I know that it is possible to check the length of the scalar and append it in case it is uneven, like below, but is there a cleaner way where I can let unpack handle it automatically when needed?

# What I'm trying to avoid before running unpack:

if (length($input) % 2)) {
    $input .= "\0";
}

Solution

  • You can add the null byte every time, it will be ignored when the amount of bytes is even.

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    use Test::More tests => 2;
    
    sub Unpack {
        my $input = shift;
        [ unpack 'S*', "$input\0" ]
    }
    
    is_deeply Unpack("abcde\0"), [25185, 25699, 101];
    is_deeply Unpack("abcde"),   [25185, 25699, 101];