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


In reply to Function to produce formatted ord values of a string by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.