Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^2: Perl is more intuitive

by kiat (Vicar)
on Aug 19, 2005 at 11:44 UTC ( #485082=note: print w/ replies, xml ) Need Help??


in reply to Re: Perl is more intuitive
in thread Perl is more intuitive

That looks very clean. And I supposed the each is a good-enough contextual clue that a hash is being called.


Comment on Re^2: Perl is more intuitive
Re^3: Perl is more intuitive
by Joost (Canon) on Aug 19, 2005 at 11:57 UTC
    each is actually a method name that's used for many of the container types; arrays use it too:

    arr.each { | x | # iterates the elements, NOT the index puts x }

    Basically, each here is just a method that recieves a block (like perl's anonymous subroutines) as an argument. The container type is then responsible for calling the block for each element.

    Any class can provide it's own each method - this is not a built-in function like perl's foreach.

      Ah, I see.

      Then if I'm new to the language and I'm reading someone's code, it may be harder for me to understand what's going on, unless the variables are named such as to give a hint e.g. arr_grades, hash_address.

        That's true, but rubys library design is based on the idea that you should not tie down the type of a variable in the syntax, because if you do that, polymorphism becomes a lot more difficult (c.f. Java's interfaces, or C++'s multiple-inheritance).

        Take this simple function:

        def print_all(array) array.each do |el| puts el end end

        The name of the parameter is "array", but because there is no type indication, this will work just as well with a File (print each line) a Set (print every element of the set), a Struct or some other object that happens to have an each() method that works like this. According to the idiom, an each method should "walk through" a collection - as long as you use idiomatic design, your code will remain relatively easy to interpret.

        I like this strategy, but as you noted, it does have some drawbacks if you want to figure out what a complex piece of code does exactly, or when the idiom is broken.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://485082]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (16)
As of 2014-07-30 15:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (235 votes), past polls