in reply to using format twice

This is some of the uglyest code I've seen posted on PerlMonks! There is absolutly no need for any of the gotos that are scattered all through the code!

The following does what you seem to want to do without the gotos and without the troublesome format stuff:

#!/usr/bin/perl -w use strict; use warnings; print "Packaged Goods Organizer\n========================\n"; my %val; my $total=0; while (do {print "Barcode : "; $_ = <DATA>}) { chomp; last if ($_ == "0" || ! length); if (($_ >= 10_000_000_000) || ($_ < 1_000_000_000)|| /[^0-9]/){ print "Bad input (numbers only and between 1000000000 and 9999 +999999)\n"; next; } my $code = $_; while (do {print "Price : "; $_ = <DATA>}) { chomp; if (/[^0-9\.]/) { print "Numbers only\n"; next; } $val{$code}{"Price"}= $_; last; } while (do {print "Quantity : "; $_ = <DATA>}) { chomp; if (/[^0-9]/) { print "Numbers only\n"; next; } $val{$code}{"Quantity"}= $_; last; } }; print "\n\n\t\tGoods in Stock\n\t\t==============\nBarcode Price +Quantity Value\n-----------------------------------\n"; for (sort keys %val){ my $value = $val{$_}{"Price"} * $val{$_}{"Quantity"}; printf "%10d%8.2f%9d%8.2f\n", $_, $val{$_}{"Price"}, $val{$_}{"Quantity"}, $value; $total += $value; } printf "-----\nTotal value in stock \$%.2f\n", $total; __DATA__ 1231231231 21 2 1231231232 44 2 0

Prints:

Packaged Goods Organizer ======================== Barcode : Price : Quantity : Barcode : Price : Quantity : + Barcode : Goods in Stock ============== Barcode Price Quantity Value ----------------------------------- 1231231231 21.00 2 42.00 1231231232 44.00 2 88.00 ----- Total value in stock $130.00

Note that the <DATA> uses should change to <> to get the data from stdin per your original code. I was too lazy to type the values in so opted for __DATA__ doing the work for me.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: using format twice
by doc_faustroll (Scribe) on Apr 05, 2006 at 03:26 UTC
    Can I commend you to sainthood for that act of compassion? You remind me of Buddha vanquishing return of the frightening demon "GOTO" with the sword of discrimination, restoring sanity.

    However, "uglyest" fails my English language parser. Although one never knows around here whether something is intentional or not, so perhaps you were merely mirroring the uglyness, as in UGLY, of that code you cleaned up.
      Doc--

      I think he meant "Hideoust" 8^)

      --roboticus

Re^2: using format twice
by zer (Deacon) on Apr 05, 2006 at 03:41 UTC
    ya as ugly as my code is............. yaaaaaaa..... no comment

    BTW with the printf "%10d... it errors on numbers like 90000000000... part of the reason im doing this in perl and not C *shudders*

      No problem there. Change it to printf "%10s. That would work for C too. :)


      DWIM is Perl's answer to Gödel
        which data type is that?