Stumbled on some code today that I didn't like very much.
Two possible improved implementations are shown in the test program below.
How would you do it?
use strict;
use warnings;
# Original function.
# Given an input string $buf, return a string of its ord values
sub old_dump_buf {
my $buf = shift;
my $out;
for (my $x = 0; $x < length($buf); $x++) {
$out .= sprintf("%3d ", ord(substr($buf, $x, 1)));
}
return $out;
}
# Possible improved implementations follow. How would you do it?
sub new_dump_buf_1 {
my $buf = shift;
return sprintf '%3d ' x length($buf), unpack( 'C*', $buf );
}
sub new_dump_buf_2 {
my $buf = shift;
return join ' ', map { sprintf '%3d', $_ } unpack( 'C*', $buf );
}
my $testdata = join '', map { chr } 0..255;
my $old = old_dump_buf($testdata);
$old =~ s/ +$//;
print $old, "\n";
my $new1 = new_dump_buf_1($testdata);
$new1 =~ s/ +$//;
$new1 eq $old or die "oops old != new1";
my $new2 = new_dump_buf_2($testdata);
$new2 eq $old or die "oops old != new2";