Underscores in numbers

By Adrian Smith26 Apr 2012300 words1 mins to read

One feature I miss from my Perl days, which I've never seen in another language. I am writing a test loop and I want it to run 10k times. So I write, in Java:

for (int i = 0; i < 10000; i++) { ... }

Nothing surprising about that. But in Perl I could write:

for (my $i = 0; $i < 10_000; $i++) { ... }

You can put underscores anywhere when writing number literals, and they will get ignored by Perl. So you can make such large numbers a lot more readable.

It isn't a huge feature, it could easily be implemented by other languages such as Java, only..... it isn't. The fact that it would be easy to implement only adds to the existing annoyance created by the lack of the feature itself.

However I only have one criticism of this feature and that's that you can put the underscores anywhere. Therefore it's possible to write 10_0000 which looks a lot like 10k. I think I would limit the use of underscores only to every 3 digits. Otherwise the feature (increased readability) would have exactly the opposite effect.

UPDATE: Great news, Java introduced this feature as well.

This article was written by Adrian Smith on 26 Apr 2012

Follow me: Facebook | Twitter | Email

More on: Perl | Java | Coding | Language Design