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

Re: [Fun With Perl] Rewrite and simplify redux



On Fri, Jun 11, 1999 at 04:04:00PM -0700, Vicki Brown wrote:
> #    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];

One-element array slice in scalar context.

> 	      print (OUTF "SEQ ID NO: $pairs{$cloneid} ($cloneid)");
> 	  }
> 	  $i = $i + 1;
> 	  while (@ids[$i]) {
> 	      $cloneid = @ids[$i];

One-element array slice in scalar context.

> 	      print (OUTF ", SEQ ID NO: $pairs{$cloneid} ($cloneid)");
> 	      $i = $i + 1;
> 	  }
> 	  print OUTF "\n";

Rather an ugly work-around just to avoid the trailing comma...


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

Better...

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

Getting there...  foreach() is an obvious improvement.  sprintf is
overkill, though.  Also, that one overwrites the @ids array.


> # Other ways to do it?

Same idea, but all on one line:

print OUTF join(', ', map { "SEQ ID NO: $pairs{$_} ($_)" } @ids), "\n";


Ronald