eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:
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";
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Function to produce formatted ord values of a string
by BrowserUk (Patriarch) on Apr 20, 2012 at 09:43 UTC | |
Re: Function to produce formatted ord values of a string
by jwkrahn (Abbot) on Apr 20, 2012 at 09:02 UTC | |
Re: Function to produce formatted ord values of a string
by rovf (Priest) on Apr 20, 2012 at 08:08 UTC | |
by brx (Pilgrim) on Apr 20, 2012 at 10:09 UTC | |
by rovf (Priest) on Apr 20, 2012 at 15:10 UTC | |
Re: Function to produce formatted ord values of a string
by GrandFather (Saint) on Apr 20, 2012 at 12:52 UTC | |
Re: Function to produce formatted ord values of a string
by Anonymous Monk on Apr 20, 2012 at 08:30 UTC | |
Re: Function to produce formatted ord values of a string
by Anonymous Monk on Apr 20, 2012 at 08:41 UTC |
Back to
Seekers of Perl Wisdom