From: Peter Hickman Date: 2002-08-28T17:43:37+09:00 Subject: Re: Converting Perl scripts to Ruby? Tim Hammerquist wrote: >I'm not sure why you value name real estate so highly. Var names >aren't like file descriptors. And with a language as robust as >Ruby, space used for variable names can't possibly be the largest >drain on resources. Namespace real estate can't be at that much >of a premium either, because in both the Ruby and Perl examples, >the variable goes out of scope as soon as the iteration finishes. > It's not something as esoteric as namespaces but just the use of meaningful variable names within code. A lot of the code I come across might use $x as a loop variable, and then $y (we are talking Perl here obviously) to hold some intermediate variable. Then a loop appears inside the first loop with $z and $xx. Before you know it you have many variables with pointless names that actually do nothing usefull. It is not that $x is a bad variable name because if you have $loop_counter, $another_loop_counter, $loop_counter2 and $yet_another_loop_counter you are really none the wiser. If a variable exists then it must be named and in my experiance programmers (myself included) can be very bad at giving meaningful names to variables especially in code that evolves over time. Then it was just a single loop then $x was a reasonable variable name, but after a year or so then $x is meaningless as several loops have been added to the code. The less variables you have to name the greater the chance of giving them a meaningfull name. > >How do you mean "surrogate"? And no, the idiomatic styles of >languages is not identical. Where ruby uses #each, perl uses a >foreach loop. But these _are_ the idiomatic equivalents for the >same procedure. > A surrogate variable represents nothing by itself but is required to write the code. For example in basic. FOR x = 1 TO 10 PRINT "Hello world" NEXT x All you want is a loop that runs 10 times but you are forced to create and name a variable you have no use for. Whereas in Ruby we have (10).times { puts "Hello world\n" } No surrogate variable. Also to swap 2 variables $a and $b. $c = $a; $a = $b; $b = $c; $c is a surrogate and exists just to facilitate the code. ($a, $b) = ($b, $a) No surrogate variable. When you debug or upgrade code you have to take into account every variable so it helps if the code contains the least number of variables that it can. With throwaway variables like $c you may find that because the swap no longer needs it the programmer then reuses it in a longer term context later in the code and we have a variable suffering multiple personality disorder. "Ah yes $x is a loop counter (twice), the total income tax to date and the id of the highest paid salesman this month". It's a whole world of pain.