From: Tim Hammerquist Date: 2002-08-28T18:23:46+09:00 Subject: Re: Converting Perl scripts to Ruby? Peter Hickman graced us by uttering: > Tim Hammerquist wrote: > > 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. Thank you for explaining. I think I understand what you mean now. No, I suppose Perl doesn't have any way to truly perform anything 10 times without a "surrogate" var. The closest I can get off the top of my head is: foreach (1..10) { do_something } Yes, it sets the implicit $_, but even Ruby's "(10).times" creates an anonymous Fixnum. The biggest waste in the above code is that it creates a temporary anonymous list of 10 actual integers over which to iterate, all of which are tossed away, their value never actually processed. So, in the end, we still haven't saved your surrogate var from existence ($_), though even Ruby sets $_ transparently with every call to File::gets. We have, however, saved "valuable name real estate". Like I said, I also believe Ruby to be superior. I just don't like making the case using contrived Perl code that uses even more "surrogate" vars than are necessary. IOW, when comparing code of different languages, at least compare _good_ code from each language. :) > 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. Should I deduce from this that you never use the $_ var in Ruby? In all honestly, I use it very little myself, even with my Perl background. > "Ah yes $x is a loop counter (twice), the total income tax to > date and the id of the highest paid salesman this month". With a name like $x, I'd hope that it were an entirely local and throw-away var in each context. This is, of course, wishful thinking in most cases. ;) > It's a whole world of pain. ....when people don't know their own language. ;) Cheers! Tim Hammerquist -- Usenet is essentially a HUGE group of people passing notes in class. -- R. Kadel