When writing the script posted in this reply I originally tried to use unpack to extract each line after sorting but it mashed the output into a single line with no line feeds. (I went with substr instead). The documentation states that unpack does the reverse of pack but using the 'A' template seems to lose trailing newline characters when unpacking. Embedded newlines are preserved. Using the 'a' template instead works as expected.
use strict;
use warnings;
use feature qw{ say };
use List::Util qw{ max };
my $string = qq{abc\n};
my $packed = pack q{A*}, $string;
my $unpacked = unpack q{A*}, $packed;
say
$string eq $packed
? q{OK - original and packed are the same}
: q{Not OK - original and packed differ};
sideBySide( $string, $packed );
say
$string eq $unpacked
? q{OK - original and unpacked are the same}
: q{Not OK - original and unpacked differ};
sideBySide( $string, $unpacked );
say q{=} x 50;
$string .= qq{def\n};
$packed = pack q{A*}, $string;
$unpacked = unpack q{A*}, $packed;
say
$string eq $packed
? q{OK - original and packed are the same}
: q{Not OK - original and packed differ};
sideBySide( $string, $packed );
say
$string eq $unpacked
? q{OK - original and unpacked are the same}
: q{Not OK - original and unpacked differ};
sideBySide( $string, $unpacked );
sub sideBySide
{
my( $original, $modified ) = @_;
my @origChars = map { sprintf q{%#02x}, ord } split m{}, $original
+;
my @modChars = map { sprintf q{%#02x}, ord } split m{}, $modified
+;
my $nRows = max scalar( @origChars ), scalar( @modChars );
for ( 1 .. $nRows )
{
printf qq{%8s%8s\n},
scalar @origChars ? shift @origChars : q{},
scalar @modChars ? shift @modChars : q{};
}
}
The output.
OK - original and packed are the same
0x61 0x61
0x62 0x62
0x63 0x63
0xa 0xa
Not OK - original and unpacked differ
0x61 0x61
0x62 0x62
0x63 0x63
0xa
==================================================
OK - original and packed are the same
0x61 0x61
0x62 0x62
0x63 0x63
0xa 0xa
0x64 0x64
0x65 0x65
0x66 0x66
0xa 0xa
Not OK - original and unpacked differ
0x61 0x61
0x62 0x62
0x63 0x63
0xa 0xa
0x64 0x64
0x65 0x65
0x66 0x66
0xa
My questions: is this a bugette, a feature, or am I having a senior moment?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.