in reply to Align string on a 32-bit boundary with padding
Use pack with the Z template.
Update: An example.
johngg@aleatico:~$ perl -Mstrict -Mwarnings -E ' my $str = q{example.me}; my $length = length $str; my $padTo = 4; my $rem = $length % $padTo; my $padLen = $length + ( $rem ? $padTo - $rem : 0 ); print pack qq{Z$padLen}, $str;' | hexdump -C 00000000 65 78 61 6d 70 6c 65 2e 6d 65 00 00 |example.m +e..| 0000000c
Update 2: Don't use this, if the string is already aligned to a 32-bit boundary the Z template will overwrite the last character with a NULL is it seems to always produce a C-style NULL-terminated string.
Update 3: Removed the strike-through! The solution is to only pad with pack when necessary but it does begin to look messy.
johngg@aleatico:~$ perl -Mstrict -Mwarnings -E ' my $str = q{myexample.me}; my $length = length $str; my $padTo = 4; my $rem = $length % $padTo; print $rem ? pack( qq{Z@{ [ $length + $padTo - $rem ] }}, $str ) : $str;' | hexdump -C 00000000 6d 79 65 78 61 6d 70 6c 65 2e 6d 65 |myexample +.me| 0000000c
Cheers,
JohnGG
In Section
Seekers of Perl Wisdom