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

Re: [Fun With Perl] Puzzler (should this work?)



On Sat, Jun 12, 1999 at 01:53:00PM -0700, Vicki Brown wrote:
> # This one seemed perplexing at the time...
> #
> # Does it work? If so, why? If not, why not?
> # Should it work? What's going on?
> #
> # I posted this to comp.lang.perl.moderated about 6 months ago... it was
> # politely suggested that the programmer try C :-)
> 
> # Original code
> 
> print "entry: ";
> START: while(<STDIN>){
> 	chomp;
> 	$id = read_id_line($_);
> 	print "test id = $id\n";
>      print "entry: ";
> }
> 
> sub read_id_line() {
> 	shift;
> 	# >gi|319118|gb|L18858|L18858 MUSM1537RE Mouse
> 	if (/^>gi\|([0-9]+)[ |][.\n]*/) { return $1 }
> 
> 	# >5H1A_HUMAN/53-400
> 	 if (/^>([0-9A-Z_]+)\//) { return $1 }
> 
> 	# >Contig[0001], 825 bases, 8988 checksum.
> 	if (/^>Contig\[(\d+)\], /) {
> 		 $val = "contig$1";
> 		 return $val;
> 	}
> 	/^>(\w+)/;
> 	return $1;		#generic
> } #read_id_line
> 

It does work.  There are two reasons it should not; the argument is shifted
from @_ and ignored, and the subroutine is called with an argument but was
declared with a null prototype.

Even though the argument in @_ is ignored, the argument was already in $_
from the calling code.

Even though the subroutine was declared with a null prototype, the
subroutine call was compiled before the subroutine declaration, so the
prototype was not yet known.


However, the code uses $1 without verifying the success of the match.  
If the regex /^>(\w+)/ does not match, then $1 from the last successful
match in the calling code will be returned.


Ronald