[Omaha.pm] sprintf is your friend

Daniel Linder dan at linder.org
Mon Aug 28 07:41:46 PDT 2006


On Fri, August 25, 2006 15:47, Jay Hannah wrote:
> Before:
>
> sub prepend_pegheader
>   {
>     my ($str, $msgtype) = (@_);
>     my $len = length($str) + 6;
>     $len = "00000" . $len;       # Just slap 5 zeroes onto the front and
> only
>     $len =~ s/^\d+(\d{5})$/$1/;  # take the last 5 characters.
>     $str = "$msgtype$len$str";
>     return $str;
>   }

I don't like this -- it seems to use a lot of extra steps to achieve the
same result.  I'd only use this over the other one if it was faster and
that was a paramount issue in the program.

The only place I can realistically see this breaking is if "len" is >99999
- thus only the last five digits of the real number would get captured. 
At least with "sprintf" it will expand the "%05d" to show all six digits
if needed.  Of course that might be the intent so that the sixth column is
*always* the start of "str" nomatter what.

dan at dglinder:~/tmp$ cat d.pl
#!perl -w

$number = 123;
$line = sprintf ("1: %05d\n", $number);
printf ("%s", $line);

$number = 123123;
$line = sprintf ("2: %05d\n", $number);
printf ("%s", $line);

dan at dglinder:~/tmp$ perl ./d.pl
1: 00123
2: 123123


> After:
> sub prepend_pegheader
>   {
>     my ($str, $msgtype) = (@_);
>     my $len = sprintf("%05d", length($str) + 6);
>     return "$msgtype$len$str";
>   }

This is my pick, even if it is a slight bit slower in the end -- much more
readable.  If you do get six digits showing up where you only wanted five
then I would recommend that you check why the length of "str" is so great,
and either adjust the five digits to six or larger, or fix the input being
placed into "str".

Dan


- - - -
"Wait for that wisest of all counselors, time." -- Pericles
"I do not fear computers, I fear the lack of them." -- Isaac Asimov
"Soon we will be able to harness the rotational energy from Orwell's grave
to solve all world energy problems." -- /. user GigsVT (208848)
GPG fingerprint:6FFD DB94 7B96 0FD8 EADF  2EE0 B2B0 CC47 4FDE 9B68



More information about the Omaha-pm mailing list