miércoles, 28 de enero de 2009

Net simulator toy problem in Io

Another little test in Io language.

Packets are generated in a node with a content and a destination. Nodes are linked in a ring and passOn packages unless the package is for themselves.

Next versions to come, with subclassed nodes and more tests.

Syntax highlighted version in http://pastie.org/373095

Packet := Object clone do(
content := nil
destinatary := nil
)

Node := Object clone do (
id ::= nil
next ::= nil
generate := method(content, dest,
a := Packet clone
a content = content
a destinatary = dest
#a destinatary println
passOn(a)
)

receive := method(packet,
("I'm ".. self id .. ". The packet goes to".. packet destinatary .. "") println
if(packet destinatary == self id,
("I've received a package with the message:".. packet content .. "") println ,
#if (packet content asString containsSeq("sleep") and self id == 4, wait(2)) #nonblocking? anyone?
passOn(packet)))

passOn := method(packet,
#self id asString println
if(self next != nil, r:= self next receive(packet), "WTF?! I've no next node!" println))
)

lista := List clone
lista append (Node clone do (setId(0)))

for(i,100,1,-1,
lista append(Node clone do(setId(i) setNext(lista at(lista size -1)))))

lista at(0) next = lista at(lista size-1)
l1 := lista at(0) generate("matat1",45)
#l2 := lista at(0) generate("matatsleep",65)
#l3 := lista at(0) generate("matat3",20)
Future Work is Handling packages in a thread (and learning how to use futures), to be able to block some packages in certain nodes but be able to continue passing nodes along while processing (blocking) a given package.

That would allow having many packages navigating the 'net'.

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
   }
}