What is the name of the implicit variable in a java while loop?
In Perl you can write something like
while(!eof){
doSomething(x,y);
print $_;
}
and the second statement prints out the iteration the loop is up to using $_
, the name of the invisible variable Perl uses to iterate through the loop. What is the name of that开发者_JS百科 variable in Java?
I realise that you can accomplish the same thing by declaring a variable outside the loop and incrementing it, but this way is definitely more elegant if anyone knows how to do it.
There's no implicit variable in Java as in Perl. You just have to be more explicit in Java...
There is no such concept in Java.
In Groovy, at least you get an it
variable set on the functional methods.
myList = [1,2,3];
myList.each {
println it
}
or to read a file, like in your example...
new File('test.txt').eachLine {
println it
}
You are mistaken; perl does not implicitly do anything with $_ in the while loop you show.
You are either thinking of for/foreach loops, where $_ is the default iteration variable if you do not specify one, or of the special case of a while with the expression being a readline or glob operation, where an assignment to $_
is added for you.
you can even be more implicit:
foreach (<LINE>){
doSomething(x,y);
print; #If you don't specify what to print, it prints "$_"
}
However, what was once acceptable is no longer acceptable. It's much like not using use strict
and use warnings
in your code. Not using these pragmas allowed you to do so many interesting things. Things that you might not have intended to do and things that make your code really hard to understand.
Almost all Perl programmers no longer use the implicit $_
and @_
because it's just makes your code all that more difficult to understand and can be a cause errors (like assuming that while
also uses an implicit $_
;-) ).
Java (and most languages) don't have such a default variable because it's not really all that good an idea. Good Perl ideas like CPAN and expanded regular expressions have now been copied in other languages. Things like default variables have not.
Using this stuff can be fun -- like a secret decoder ring that allowed you to know who's a real Perl hacker and who isn't. It's fun to read through all that obfuscated Perl code and see who really understands the inner workings of Perl.
However, it has also given developers in other languages the proof they need that Perl was hopelessly sloppy and impossible to understand. And, as a result, Perl has suffered in general acceptance.
精彩评论