miércoles, 21 de enero de 2009

a couple of perl gotchas

Yesterday I spent long time trying to catch 2 bugs in my code. It's not that perl is bad documented but me keeping forgetting things, so I'll put how did I solve them.

First one: perlvar are GLOBAL

Being used to use $_, you always find it has the correct value, so rarely localize it (only in nested loops for me). But I was setting $/ line separator to paragraph mode ($/="";) in a function, and though when I exited that block it would be set to the $/ value of returning blog.

FALSE: you should localize $/ in order not to interfere other parts of the module, nor other modules using $/.

local $/="";


Other one is looks_like_number from Scalar::Util.

I was using the flip-flop operator in scalar constant, and somewhat remembered something of returning an 'E' on the last line that matched. I used looks_like_number to check that, but.. omg! "23E0" looks like a number! It makes sense, but I didn't thought of it at first.

while(<>){
  $range = /foo/ .. /bar/;
  if(looks_like_number($range) && $range !~ /E/ && $range>2 ){
   #do things
   }
}

No hay comentarios: