Rite, Block locals and Autovivification

J

John Carter

Perl has what may be an evil solution block locals.

Certainly maximal surprise but Does What I Mean....

What does the bit of Perl
$a{foo}++
do?

Well, you clearly are referring to a hash, so it makes one.

Since foo doesn't have a sigil, it takes it as a string...
$a{'foo'}++

Since the element doesn't exists yet, and we're adding one to it, it
"autovivifies" or "magically grants life" to it. Namely 0. Perl chose 0
since that is "What I Mean" when I add one to and uninitialised something.

Now to Ruby...

def each_anime(io)
io.each do |line|
next unless line =~ /evangelion|omg|spirited/
l = line.length # l is just local to block
map[$1] = line # Autovivifies map as Hash
count += 1 # Auto vivifies as 0 on first pass, an gives it scope
# beyond block.
weight *= 0.2 # Autovivifies as 1

yield line
end
# l is out of scope here
[count,weight,map] # Visible at function scope as autovivified.
end



John Carter Phone : (64)(3) 358 6639
Tait Electronics Fax : (64)(3) 359 4632
PO Box 1645 Christchurch Email : (e-mail address removed)
New Zealand

A Million Monkeys can inflict worse things than just Shakespeare on
your system.
 
G

gabriele renzi

il Tue, 2 Dec 2003 06:35:18 +0900, John Carter
Perl has what may be an evil solution block locals.

Certainly maximal surprise but Does What I Mean....


Just my personal feeling.. but I'd hope to avoid stuff like this in
ruby.
It is fun, powerful and absolutely intrinsic and hard to understand.
[1]

I'm not saying this is really bad, just I'd prefer this does'nt
appear.
I strongly believe 'explicit is better than implicit'.
plus, a single line:
map, count,weight={},0,1
would make this work. Not so much a big cost for me :)


[1]
If you're going to say 'no, let me explain, this is really clean and
intuitive' please consider that i really think this is hard to grasp
:)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top