[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[Fun With Perl] Rewrite and simplify redux



#    Data:

#	apple, banana, cabbage, dillpickle, eggplant, fig, grape

#	Problem:

# 	Same data; after breaking it up, reformat it and put it back together
# 	The resulting output is again one long line, ", " separation
#
# 	Note that there is an intervening step in which another hash (assoc.
# 	array) called pairs is set up...
#
# 	Original Code:

	  #
	  # Work around to stop the comma from printing at the end of the file.
	  #
	  $i = 0;
	  if (@ids[$i]) {
	      $cloneid = @ids[$i];
	      print (OUTF "SEQ ID NO: $pairs{$cloneid} ($cloneid)");
	  }
	  $i = $i + 1;
	  while (@ids[$i]) {
	      $cloneid = @ids[$i];
	      print (OUTF ", SEQ ID NO: $pairs{$cloneid} ($cloneid)");
	      $i = $i + 1;
	  }
	  print OUTF "\n";


#	First replacement:

	  foreach ($i = 0; $i < @ids; $i++) {
	      if ($ids[$i]) {
	         $cloneid = $ids[$i];
	         # an 'if' is cheaper than duplicating the assignment and print
	         # statements and risky an error if only one copy is updated
	         print (OUTF ", ") if ($i > 0);
	         print (OUTF "SEQ ID NO: $pairs{$cloneid} ($cloneid)");
	     }
	  }
	  print OUTF "\n";


#	Second replacement:
#	(or, if 'split' is your friend, join should be your buddy too)

	  # reformat...
	  foreach $id (@ids) {
	      $id = sprintf("SEQ ID NO: %s (%s)", $pairs{$id}, $id);
	  }

	  # and join together again...
	  $line = join(', ', @ids);

	  print("$line\n");

# Other ways to do it?
-- --
        |\      _,,,---,,_       Vicki Brown <vlb@cfcl.com>
  ZZZzz /,`.-'`'    -.  ;-;;,_   Journeyman Sourceror: Scripts & Philtres
       |,4-  ) )-,_. ,\ (  `'-'  P.O. Box 1269  San Bruno  CA  94066
      '---''(_/--'  `-'\_) http://www.cfcl.com/~vlb  http://www.macperl.org

==== Want to unsubscribe from this list? (Don't you love us anymore?)
==== Well, if you insist... Send mail with body "unsubscribe" to
==== fwp-request@technofile.org

</x-flowed>