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

RE: [FWP] Problem - rewrite and simplify



Vicki Brown wrote:

> #    Data:
> 
> #	apple, banana, cabbage, dillpickle, eggplant, fig, grape
> 
> #	Desired result:
> 
> #	Break the data into fields; fields are separated by ", "
> #	Store each field separately
> 
> # Problem -
> 	# The original code will lose the last entry on the 
> line iff the data
> 	# file ever contains more than one line.
> 
> # Original code:
> 
> 	  #
> 	  # Initializations
> 	  #
> 	  $count = 0;
> 	  @ids = ();
> 	  #
> 	  # Read the Cloneids into an array called ids
> 	  #
> 	  while ($line = <CLONEIDSLIST>) {
> 	    chop ($line);
> 	    until (index($line, ', ',0)< 0) {
> 	         $ids[$count++] = substr($line,0,index($line,', ',0));
> 	         $line = substr($line, index($line, ', ',0) + 2);
> 	    }
> 	    $ids[$count] = substr($line,0);
> 	  }
> 
> 
> 
> # Replacement code :-)
> 
> 	  #
> 	  # Read the Cloneids into an array called ids
> 	  #
> 	  while ($line = <CLONEIDSLIST>) {
> 	     chop($line);
> 	     push(@ids, split(/, /, $line));
> 	  }
> 
> 
> # The replacement code never loses an entry.
> 
> # I didn't see the need to initialize the (guaranteed to start out
> # empty)  @ids.
> 
> # Better ideas??

Why chop (or chomp) when you don't have to?

push( @ids, split(/, |\n/, $line)) while ($line = <CLONEIDSLIST>);

==== Want to unsubscribe from Fun With Perl?
==== Well, if you insist... Send mail with body "unsubscribe" to
==== fwp-request@technofile.org