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";
-
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.
|