Hacker News new | past | comments | ask | show | jobs | submit login
A little thing to love about Perl 6 and COBOL (perl.org)
174 points by i_cannot_hack on Feb 4, 2015 | hide | past | favorite | 129 comments



I think the thing that would make perl 6 really successful would be to call it something other than perl. Many people who have programmed perl for a long time seem to think it is an abomination of the first order, many people who have never programmed in perl think perl is some sort of dead language like COBOL or PL/1. Both groups are going to have a systemic aversion to this new language simply based on its name. And that is unfortunate.

There are neat things in this new language and there is no reason to leave the sea anchor of a name attached to it. Call it something fresh and new and it can be the cool hotness that is up and coming.


The avalanche has already begun, it is too late for the pebbles to vote.

Everyone knows it as Perl 6. Therefore, everyone who would write about it after this proposed name change would say "formerly known as Perl 6," so that people know what you're talking about. All the conceptual baggage remains.

(And the reason the Perl name is a boat anchor is because someone hooked a chain to it and sank it to the bottom of the ocean. Perl didn't die from natural causes, Perl was killed by neglect - neglect caused because Perl 6 was always right around the corner and why sink more effort into maintaining Perl 5 than was absolutely necessary? So now OG Perl is stuck on 5.x from now until the heat death of the universe, because this project poisoned the well.)


> The avalanche has already begun, it is too late for the pebbles to vote.

thanks for the deep words, Kosh


I apologize for being out of the loop, but who's Kosh?


Kosh is a character on the TV show Babylon 5. It's where the quoted line is from.


If he googled he would have even found a Youtube version of the quote.

http://youtu.be/g1GF4Gnb-D0


> Perl 6 was always right around the corner and why sink more effort into maintaining Perl 5 than was absolutely necessary?

What are you talking about? ( http://perldoc.perl.org/index-history.html ). A lot of the releases in the last decade were inspired by Perl 6 features. And Moose is clearly inspired by Perl 6.

I've spoken with people who believe the last Perl release was 5.8 (released in 2002). I believe this is caused by many Linux distributions still shipping old copies of Perl 5, but it's incredibly annoying.


I don't know what the right answer is here, but I find it intriguing that this approach is in a way the opposite of what Python ended up doing with the 2/3 split.


Like many things that we love about Python, I believe it came about as a reaction to Perl. Because I'm pretty sure Perl 6 has been in development since I began learning Ruby, in 2005. That means the entire time I've been a Ruby developer, this project has been in development. I'm honestly surprised that it's being released at all.


I have great fondness for Perl, think the the innovations present in P6 are great, and even I agree with you whole-heartedly: continuing to call it "Perl 6" is a terrible strategic blunder. The redeeming factor is that a great name is already in common use: just officially rename it to "P6". It carries practically no stigma while acknowledging the legacy.


Why not Perl 2000? It's both futuristic and original.

I don't think the name is the problem, I think that there is just too much competition among languages. If you ask a younger person which language they want to learn, will they think of Perl at all? Where is it used? Everywhere isn't an answer, Web or application programming or Apps are answers. What can I use instead that recruiters think is cool/relevant is also a fair question, albeit a simultaneously stupid one.


Maybe I'm missing sarcasm. Perl 2000 is the definition of out of touch. 2000 was fifteen years ago.


2000 was when the Perl 6 effort started.


"Perl 3000" then! That should do it!


Then Perl 6 aka 2000 would share the fate of Wordstar 2000. But I guess it will anyway.


Might get a bit confused with P5 (Processing).


P6!


P6 is a sick as fuck name. They need to do this.


It's been so long that Perl is just a language most people might have heard about but probably never used. The name isn't a marketing issue.

Perl may even have some of that Lispy retro-mystery.


I think Larry Wall once suggested it converge on perl 2π (progressively approaching 6.2831853071).

Not sure about the marketing value, but it's properly geeky.



Very similar to what Knuth did with Tex. I like it.


Actually, I think that, for exactly that reason, it's a wrong idea. Knuth's numbering is meant to suggest that, except for minor corrections, TeX is in its final form. I can't imagine Larry Wall ever feeling that way about Perl.


At his FOSDEM talk, he actually talked a little about how Perl 6 should be flexible enough to keep on changing basically forever... given that you can edit the parser even on the fly, it seems plausible.


I'm certainly one who would rather learn Go or Ruby instead of Perl. Because I already know quite a lot Python and a little PHP, AWK and Bash I don't think I'll ever run into a usecase where learning Perl would be worth more than implementing a solution in e.g. Bash+Python+AWK. Around me the people all know these three languages better than Perl (or at least think so). Giving Perl6 a new name would certainly help in making it more interesting.


> I don't think I'll ever run into a usecase where learning Perl would be worth more than implementing a solution in e.g. Bash+Python+AWK.

that might be also because you are not familiar with perl6 though, a form of blub paradox.

I.e. are perl6 grammars better for parsing than anything available for python? Maybe or maybe not, but one needs to know them before being able to judge.


I was playing around on hackerrank the other day as practice for a job interview using it. I haven't used Perl for 4 year, since I moved to Python, but all the problems i looked at seemed like they would be easier to do in Perl. Autovivificvation, and features built into the syntax just made certain things way easier. It was all doable in python, but you needed to do more checking.


The reason I've written that comment is that I believe Perl lovers can, based on feedback like that, make better decisions about how to present their favourite language to the world. So if I would read a few articles on HN about how problems got solved with Perl in a way that Python wouldn't be able to, then I might start learning Perl soon. That's why I wrote that comment. Not for you guys to feel bad about your favourite language, but about helping you to present it better to people who don't know it yet.

The strong features of Perl that I know (which might be completely wrong): Regex and huge library. Both features are not distinct to Perl anymore though. Perl's regex might be a little better than Python's or AWK's but probably not enough to make it worth learning it.

And yes learning a new language to level that you not just know the syntax but also a few of the important libraries, blogs and developers is a huge task that takes several months. If you are not a student any more you really need to think hard before you commit to something like that. Sure there are people who just learn new languages for fun as a hobby. But that's not your target audience if you want your favourite language to become more popular.


> So if I would read a few articles on HN about how problems got solved with Perl in a way that Python wouldn't be able to, then I might start learning Perl soon.

That might have been the idea behind the ariginal article ("hey, Perl 6 has built in rational types").


One feature which I believe is distinctly available only in Perl 6 is it's grammar feature. ( think class/method based regular expressions that look similar to BNF )

As an example look at this Perl 6 grammar for JSON: https://github.com/moritz/json/blob/master/lib/JSON/Tiny/Gra...

Perl 6's best feature is that it combines many features from many languages in a way that allows combining them cleanly, and without any of them feeling like they were glommed on. (unlike Perl 5's object system which was inspired by Python's object system)

If you can get past the syntax differences from other languages, and program in it for a while, you may never want to go back to any other language.

If you can't get past the syntax, please say that you "don't like the syntax" instead of "it's unreadable" or "it's a write-only language" or "it's difficult to learn". ( I for one found it quite easy to learn, and can read it quickly. )

---

Really can you make all of the following examples clearer in any other single language?

  constant powers-of-two = 2,4,8 ... *; # an infinite deductive list

  # perhaps that would be more clear as:
  constant powers-of-two = 2, 4, 8, 16, 32, 64 ... *;

  # list of pairs using the zip meta-operator (Z)
  # combined with the pair constructor operator (=>)
  my @a = 'a'..'z' Z=> 0..*; # ( a => 0, b => 1, etc )
  my $new-password = ('a'..'z','A'..'Z',0..9).roll(12).join; # 'ygHIHbi4XgUV'

  # the zero in the following is to prevent an off-by-one error
  # when accessing by index
  # * + * creates a code ref that takes two inputs and numerically adds them together
  constant fibonacci-list = 0, 1, 1, * + * ... *;

   # takes about a second the first time it's accessed currently
  say fibonacci-list[10000].chars == 2090;

  # if you wanted it to look more like haskell you could write it like this:
  constant fibonacci-list = 0, 1, 1, &[+] ... *;

  my @dice-rolls := ('⚀'..'⚅').roll(*); # infinite list of dice rolls

  # deck of cards using the cross meta-operator (X)
  # and the string concatenation operator (~)

  my @deck = 2..10,<J Q K A> X~ <♡ ♢ ♣ ♠>;

  my @shuffled = @deck.pick(*);

  # ( .say ) is short for ( $_.say )
  # prints the first 6 numbers (0..5) each on it's own line
  for ^6 { .say }

  # prints the numbers 0..5 each on it's own line,
  # possibly randomized,
  # possibly each in it's own thread ( texas version )

  (0..^6)>>.say;
  (^6)».say; # ditto ( french version )

  # ( those were purposefully misusing an auto-threading list operator >> )

  # says a random number (1..5), 5 times out of 6
  if (0..5).pick -> $number { say $number }
  if (0..5).pick { say $^number } # ditto
---

That was just a sampling of the bread-and-butter constructs (some of which were used in a way that most people wouldn't use them). There are also operators for dealing with Sets for example. ( ⋃ and (elem) being two of them )

see: http://doc.perl6.org/

You can even create new operators the same way you define a subroutine ( That's all they are in the Rakudo implementation, for most of them. )

  # common factorial example
  sub postfix:<!> ( Int \n where * >= 0 ) is tighter(&infix:<*>) { [*] 1..n }
  say 5!; # 120


That is a quite convincing argumentation in favour of Perl6. Thanks! I really like this kind of code.


It is possible that this is easier than I think in Python, but here is an example where Perl made my life (and various co-workers' lives) easier. A couple of years ago I needed to copy a bunch (between 1000 and 2000) posts from an old web site to a new one. This required parsing forms on the destination site, and also stripping out tags the new site did not support. The CPAN module HTML::TreeBuilder allowed me to do this quickly and without undue difficulty.


Not everything is about utility for everyone


That's not exactly true. While its true that there issues with Perl. Its still by and large a language widely used by developers across the world. There is a also a huge and a very active community which does amazing things with it. Now taking away the name means re doing some 2.5 decades of marketing all over again. No body needs to go over that all over again.

There is a set of programmers with whom this won't go down well. Enterprise programmers and the hipsters.


don't forget the hipster enterprise programmers (aka the contractors)


how are contractors the hipsters of enterprises? if anything they're the yuppies. do whatever the fuck they want, get paid boatloads of cash, don't produce anything of value, are generally dicks. i think you're thinking of brooklyn trustfund hipsters, which are just the new yuppies.


I'm a consultant, produce plenty of value, have very happy customers, and I don't get called a "dick" too often. Don't pay all of us with the same brush, please :)

(Note: I'm the guy who wrote the post OP linked to)


Us perl contractors (former in my case, a decent job in my home town with good working conditions came up) are what the enterprise turn to when they need to circumvent the bureaucracy.


The funny thing (to me) is that a little while ago, the Perl 5 developers started talking about renaming Perl 5 as a branding issue ( http://blogs.perl.org/users/matt_s_trout_mst/2013/02/pumpkin... ).

Because, obviously, if people don't like what you made, it's just a question of what you called it.


I don't think so. The real problem with Perl is it's an aesthetic train wreck. It is possible to write beautiful Python, Ruby, Erlang, ML, Prolog, C, C++ or even Java, but I challenge anyone to write a non-trivial Perl (5 or 6) program that doesn't make you feel slightly ill.

Some of the semantics seem really nice, but the syntax is utterly disastrous.


I used to work mostly in Perl. It's true that it can easily be turned into an obfuscated mess.

But I've also written some of the most maintainable code I've ever seen in my career in Perl. One project in particular was over 30k lines long (which in non-Perl languages must be worth millions of lines of code ;).

It was put aside for a few years (4 or 5 IIR), then I had to return to it to do some maintenance and inside of an hour was able to digest the code-base, make the needed changes, test and release.

Sloppy code and poor design infects every language. Perl does make it easy, but that's because Perl has a design emphasis on one-off scripts in the same way Java has an emphasis on large-team collaboration, and write-once run-once is what makes Perl so absurdly productive.

Just like with any language, you set some code standards and some overall design principles and you can write really maintainable code in Perl.

My wife has a similar story, after learning some basic Perl, she waded into a 100k line Perl codebase and in a couple days refactored some memory intensive code to use cheaper data-structures in a memory intensive part of the code. It was no-big-deal, but that's because the original team had left things well documented and wrote along sane standards.


I hear this argument time and time again and it's simply FUD. Bad Perl is no different to bad C++ or any other language with a flexible syntax. But it's also the same visa versa.

The problem with Perl is most times people are exposed to it, it's either from code golfing sessions were code is deliberately obfuscated; or when it's basically been used as a shell scripting language and thus often written by aging Perl hackers who don't care much for code cleanliness. And sometimes people just run away screaming because they simply don't understand all the regular expressions (but to approach Perl without an understanding of Regex is a little like trying to code Java without understanding classes then moaning about the weird surplus boilerplate code)

I'm not trying to say that Perl doesn't have it's faults. It has a great many problems. But to state that Perls syntax makes it impossible to write clean code, is just a daft flamewar argument.


Hmm.

In python you have: dog.head.ears[0].hairs[123]

In perl5 you have: $dog->{head}{ears}[0]{hairs}[123]

I can see why some folks prefer the former.


Isn't that a hash? Shouldn't python version be: dog['head']['ears'][0]['hairs'][123] ?


In both Perl and Python, "object" is a glorified hash, and its attributes are entries in that hash. Python just allows for a deeper level of syntactic sugar.


In Perl a hash is any scalar value blessed into a class

In modern Perl the attibutes would be accessed through accessors so the original example needs tr/{}/()/


Perl's pseudo-objects are, in my opinion, one of the weakest aspects of Perl. So I'm not going to disagree with you that many other languages do that one thing better. But it's not always appropriate to nest your objects that deeply anyway (in any language, that can quickly become a mess).

In my personal opinion, I prefer C-style braces over whitespace formatted blocks. Which means I find reading function and iteration blocks much easier to read in Perl than I do in Python. I'm not saying one is "better" than the other, but just offering a counter argument for how subjective language aesthetics really is.


Just to counter your points, having done many years of Perl, and now a Python.

Perls OOP does feel like a bit of a hack. But it does make it transparent how everything works. I learned Java at University, and everything OOP was a black box and I had no real understanding of how it worked. After learning the Perl way, its really obvious what is going on because it is so transparent. Your current object doesn't have a method? Just look along the @ISA array until you find an object that does have it.

Pythons whitespace is a pain at first, but having used it for a few years, one problem I do not miss is loosing a brace, when reorganizing blocks of code. You cut a few lines of code and paste it somewhere above or below, and your IDE shows you you are missing a brace somewhere. The indentation looks fine, so you can't see where it is.

The whitespace thing is worth it to get rid of that problem alone.


Aren't there just as many problems with cutting and pasting python and getting either slightly off indentation or mixed spaces/tabs? If the IDE fixes the problem, I don't see why it's any different for braces as it is for whitespace. There's easy ways to identify both.


Exactly.

Arguing that one is better than the other is like arguing over which colour the best. Which is why I get so utterly sick of Perl being compared with Python - they are all going to have their strengths and weaknesses so at the end of the day, the "better" language / syntax boils down to personal preference.


I wasn't arguing that either way was better, just seeing the positives where negatives have been noted.

I personally haven't wasted anywhere near as much time with Python indentation compared to missing braces. I hated the whitespace thing at first, and it was only after going back to doing some Perl I noticed that the problem wasn't present in Python.

Though the fact that most other languages use braces is a pain, as it makes swapping between Python and Java / Perl / JavaScript / etc tricky, as I tend to get into the habit of using or not using semicolons at the end of a line.


I can't stand the '.' syntax. Someone that doesn't know python would have no idea if those are method calls or what.

And in both cases, that is terrible code. Use a class or something...goodness.


>I can't stand the '.' syntax. Someone that doesn't know python would have no idea if those are method calls or what.

How is what someone who DOESN'T know Python would think relevant?

That said, after even the smallest familiarity with the language, he sees that it's obviously not method calls unless it ends in ().

Someone who doesn't know Lisp also doesn't know what (foo 4 2) or (quote foo 4 2) is.


I'm going to disagree with you: as someone who has worked in an extensive Python codebase, based on the snippet above, I have zero clue what is actually going on. Those could just be attributes in the object, or they could be properties with arbitrarily complex code to calculate the resulting object. It could be the same object, or a freshly-allocated object, or an object that exists already. The index operator could be on a list, dictionary, or custom class with, again, arbitrarily complex code. All of that code could even be written in pure C for all I know! That single line of code could be a rats nest of a thousand lines of Python, or C, or both. And that's not even getting started with the possibility of metaprogramming or creating new classes by wrapping an existing class at runtime.

Saying that the snippet is obviously not using method calls is naive. Python is too flexible and allows programmers to do too many clever things for that, all hidden under "nice" syntax.

EDIT: Forgot a case for what that code could be doing: it could be accessing a module with globals.


>How is what someone who DOESN'T know Python would think relevant?

Because most of the people that complain about Perl don't know it either.

I have no problem reading perl code of any kind (because I know it). Perl is a beautiful language IMHO.


Well if Explicit is better than implicit then this is one example of where Perl should be the preferred!


no snark, do you have a snippet you enjoy looking at in perl?


I work with perl every day, and couldn't disagree with you more. The language is flexible enough to be anywhere from damned ugly to blessedly beautiful.

Much of the uglyiness can come from trying to write code for another language in perl syntax. Perl lets you write code that looks live Java, or C, or many other languages, but it usually ends up looking ugly. I see a lot of this.

But when you write perlish perl, especially using modern features of the language, then... yeah. It can look as beautiful as any other language.


When I first started writing perl professionally, I kept trying to write things in a lispy functional style, which only made a mess. While it's true that There Is More Than One Way To Do It, there's still such a thing as "perlish perl" and by adopting this style I ended up writing some very pleasant and easy to read code.


A long time ago I worked on a stock trading system written mostly in Perl. That code may have been a lot of things, but ugly wasn't one of them.

So, it's definitely possible to write non-trivial Perl programs without feeling ill.


I disagree, I mostly write perl for my job and I think that most of what I write is at least equally beautiful but generally more beautiful than equivalent python.


Perl 6 has lots of syntactic breadth with all the sigils, twigils, operators, composers, etc. But I feel that, as with Ruby, all the sugar really helps after you've finally made it past the initial WHUUUT? phase. Just takes a bit longer than some languages :P


The only thing I don't like about Perl, is that it's a dynamic language and therefore unsuitable for large (as in, significantly longer than will fit on the screen at one time) programs. But "use strict;" helps with that, and apparently more recent versions (work has 5.8.8) allow subroutines to more easily declare a specific number of arguments.

I'm actually learning more of it right now, so I can clean up and modularize some of my scripts. Because my other options (ksh93, Progress 4GL, and maybe older versions of Java or C++) are even less suitable.


If you haven't already, I highly suggest looking on metacpan.org for modules, and searching for highly rated[1] and recent ones. Things like Path::Tiny[2], Try::Tiny[3] and Function::Parameters[4] can make a huge difference in productivity and readability. Task::Kensho[5] is also useful for getting a good base set of medern modules to choose from for many tasks.

1: https://metacpan.org/favorite/leaderboard

2: https://metacpan.org/release/Path-Tiny

3: https://metacpan.org/release/Try-Tiny

4: https://metacpan.org/pod/Function::Parameters

5: https://metacpan.org/pod/Task::Kensho


I'll take a look at these, thanks. :)


If you planned on using objects, you can consider using Moo for roles to allow composition, and combining it with Types::Tiny for type validation. There's also Params::Validate for plain functions.

The validation is unfortunately at runtime, but at least you get a clear error instead of unanticipated behavior. Moo (and it's bigger parent, Moose) can really help you structure your application better using roles.

https://metacpan.org/pod/Moo https://metacpan.org/pod/Type::Tiny

Edit: Don't use Params::Validate; kbenson's recommendation for Function::Parameters looks awesome!


There is also Kavorka[1] as an alternative to Function::Parameters, which can use Type::Tiny types in signatures. The next step after that is Moops[2]...

[1] https://metacpan.org/pod/Kavorka

[2] https://metacpan.org/pod/Moops


You may be able to get them to update to at least 5.18.0 if you tell them about CVE 2013-1667 and all the mitigations added to 5.18.0 to prevent them.

https://duckduckgo.com/?q=CVE+2013-1667&ia=about

http://blog.booking.com/hardening-perls-hash-function.html

I would also recommend reading "Modern Perl" which is made available for free by the publisher/author at http://modernperlbooks.com/

( Also there are large codebases written in Perl ( I beleive booking.com is an example )

I also recommend installing the Perl you are using outside of the system directories. You may also find Pinto and https://Stratopan.com useful for managing your dependancies. Which is especially useful if you make your codebase modular.


I've written Python systems several tens of thousands of lines long. I don't think dynamicity has anything at all to do with a language's suitability for large projects (but if it did, I'd lean toward it making maintenance easier).


@tbrownaw... Do you mix Perl and Progress 4GL? Care to get in touch?


A little bit, yes. Contact info is in my profile now.


Are there any open source examples of beautiful C++? I don't doubt that it can exist, but I've never seen any. Maybe "beautiful for C++", but not "beautiful".

For that matter, ditto for Java. Ideal Java code seems to be "not notable", rather than "beautiful". At its best, it is clean and clear but unexciting, like a Honda Civic.


The culprit of the 'ugly Perl' meme is the $ character, all the rest is just a rationalisation of the first impression: http://perlalchemy.blogspot.com/2011/01/is-responsible-for-u...


Not to disagree with anything the OP says, but a language with somewhat more recent currency that shares the "decimals are rationals by default" advantages is Scheme (and Racket and so on). At least in Racket, floating point representation is an implementation detail of the inexact-real numbers, while the exact-rational numbers are correctly produced and computed on when you give values in decimal form.

Scheme (et al) are probably the more direct conceptual inspiration for Perl 6's rational decimals---the Perl 6 developers were certainly aware of it (as they were aware of pretty much all the major PL work out there :)


Perl 6 borrowed liberally from many sources. That does make it a very complex language, but you can omit many of the more complex features until you are more comfortable with them. There's a slide deck that touches on that point by the same author that was posted to HN recently called "Perl 6 for mere mortals" (a FOSDEM 2015 talk).

1: https://news.ycombinator.com/item?id=8953368


The problem with using floating point to represent money has nothing to do with base 2. It is that money is generally treated as something countable. If you divide a dollar in thirds the resulting third of a cent is not exactly representable in base 10 either.


Base-2 is a problem in accounting because the written value doesn't always actually numerically equal what's being represented internally. With decimal, you don't have that problem, because we write in decimal.

The bigger problem however is how precision is "managed" with floats, which leads to things like non-associativity of operations.


The article suggested hardware BCD (packed decimals) was superior to floating point. That is true but not for the reason stated. The reason old time BCD was better was simply because they were treated at counting numbers (integers). If you use binary integers you get all of the same advantages with none of the serious headaches of BCD.


Yes, but the way we write decimals doesn't represent numbers very easily, for example 10/3 can't be represented accurately with finite length decimals (but can with rationals)


Thus you'll never see anything being sold for "a third of a dollar". Accounting and finance have specific rules for rounding these, which can then be replicated with precision.


Exactly - accountants count cents (or maybe mils), they do not measure/approximate them. If I buy 2 apples at 3 for a dollar, the cost gets normalized to cents before further adding up on the bill.

Self promotion: I've written about this topic before, and there is an aspect of trying to use fractions with relatively prime denominators that comes into play - http://roboprogs.com/devel/2010.02.html


Rational-as-default seems like an odd choice. It prevents catastrophic cancellation (the ".1 + .2 - .3" from the article is an example) but at the cost of pathological complexity for some operands. For instance, summing the harmonic series (nth term is 1/n) means doing massive amounts of factoring to keep intermediate results in lowest terms...


> For instance, summing the harmonic series (nth term is 1/n) means doing massive amounts of factoring to keep intermediate results in lowest terms...

There is a feature in Perl 6 that the OP didn't mention: if the denominator doesn't fit into a 64 bit integer anymore, it falls back to floating point arithmetic.

There's a type (FatRat, http://doc.perl6.org/type/FatRat) that stays precise if you really want, but the default give precise arithemtics for "usual" numbers without pathologic slow-down for pathologic cases.


Is this kind of mixed rational/floating point sensible? It seems to be a fuzzy do-what-I-mean, not what-I-say kind of arithmetic. Surely weird differences in algorithm behaviour might occur around the 64 bit integer limit. It will also make the analysis and testing of numerical algorithm accuracy very difficult unless you can put bounds on your input values.


I feel like this "do what I mean not what I say" is exactly what I have found so irksome about Perl


I think the point is that it does what what you mean in the majority of cases. If you know you are going to need specific functionality such as floats or large rationals, specify the type of your variables up front. This is an are where the optional type system can help.


I like that the first thing the documentation says is that "class FatRat is Cool". :)

Being cool seems to mean having automatic conversion to and from strings: http://doc.perl6.org/type/Cool


How many programs written in Perl do you think add currency values together, vs. how many sum the harmonic series?


Consider computing compound interest using rationals. That's a practical thing that could happen akin to harmonic series calculation, where you'll get absurdly large rationals.


Considering .exp results in a Num, not a Rat, there's no problem here. I seem to recall this working sensibly years ago, where numerical types would coerce in sensible manner. Same happens with large denominators, so even if you roll your own successive approximation it will coerce away from Rat before things get out of hand.


You don't need factoring to add rational numbers and reduce fractions, only greatest common divisor.


And -- to be totally explicit -- although the naïve way of finding GCD is based on factoring, in fact finding GCD can be done very quickly with Euclid's algorithm, without any need for factoring.


That was my first reaction too, but I think we're reaching the point where the increased computational complexity is manageable. Efficiency has certainly never been one of Perl's selling points. I imagine there's a trapdoor available if you want to use floats anyway; actually, knowing Perl, I'm sure of it.


> Efficiency has certainly never been one of Perl's selling points.

It has been, in fact. It's been faster than Python and Ruby for a very long time (though that's changing now with some new implementations like pypy).

> I imagine there's a trapdoor available if you want to use floats anyway; actually, knowing Perl, I'm sure of it.

Yes, if you use scientific notation (1e-1 etc.) you get floating points.


There are (at least) two trapdoors. The first is that an operation on Rats which would produce a denominator which does not fit in a 64-bit unsigned integer will produce a Num instead. (If you're okay with your denominators growing in an unbounded fashion, you can use the FatRat class instead.)

The second "trapdoor" is that you can just explicitly work with Nums (ie C doubles). If your numeric literal has a exponent (eg 1e-15), it's automatically a Num. Or you can convert any Real numeric type to a Num by calling the .Num method on it.


Another language that supports this is Julia: In Julia, `/` is division, but `//` creates a rational number. Thus, in Julia, `1//10 + 2//10 - 3//10 == 0//1`, and `1 / (1//10 + 2//10 - 3//10) == 1//0`, where `isinf(1//0) == true` and `0//1 == 0`.

But the best thing is that because of Julia's type system, every subsequent operation on rationals will happen rationally as well, including (fast) linear algebra. Obviously this excludes things like `sqrt` or `fft`.

(http://docs.julialang.org/en/release-0.3/manual/complex-and-...)


> Another language that supports this is Julia:

As does, for example, scheme (tests done in racket).

    > (- (+ (/ 1 10) (/ 2 10)) (/ 3 10))
    0
    > (= (- (+ (/ 1 10) (/ 2 10)) (/ 3 10)) 0)
    #t


I prefer Python's explicit approach to decimal types:

  $ python -c "from decimal import Decimal as D; print(D('.1')+D('.2')-D('.3'))"
  0.0
Or if you prefer true rational numbers:

  $ python -c "from fractions import Fraction as F; print(F('.1')+F('.2')-F('.3'))"
  0

  $ python -c "from fractions import Fraction as F; print(F('3.1415927'))"
  31415927/10000000


What other languages call all-important features Python calls a module in the standard library :)


You could say the same thing about perl5 then :)

    $ perl -E "use bignum; say .1 + .2 - .3"
    0

    $ perl -E "use bigrat; say .1 + .2 - .3"
    0

    $ perl -E "use bigrat; say 3.1415927 / 1"
    31415927/10000000
ref: http://perldoc.perl.org/bignum.html | http://perldoc.perl.org/bigrat.html


I like the comparison to COBOL. Another IBM language of similar vintage is RPG (Report Generator) and it also uses packed decimals.

The control flow is:

- Run a set of zero or more statements once at the beginning

- Run a set of statements once per input record

- Run a set of zero or more statements once at the end

I was always struck by the similarity to:

BEGIN { ... }

while (<>) {

  ...
}

END{ ... }


Because these are two basic building blocks of 'computation', I'd say first order. It's map and reduce in disguise (or the other way around, doesn't matter).

  - [record] -> [derived from record] :: map
  - Begin and End blocks are accumulator/stateful logic :: reduce
sed is also a little twisted version of awk, per line mapping, with pattern spaces for accumulations.

It's first order, because it can't reuse itself on smaller pieces of data, namely recursion (grammars, trees, etc)


That's awk. That is literally the control flow style of awk, which Larry Wall copied into Perl very directly and entirely deliberately.

I find it very interesting that RPG uses it, and I wonder if it's convergent evolution (relative to awk and RPG) or if one is copying the other.


Interesting! I wonder what drove their decision to use rational number representation. Is it possible to turn this feature off and use floating point instead (for performance reasons, let's say)?


IIRC, there's several numeric types that conform to the larger `Numeric` type family: `Rat`, `Int`, and `Num` (which is basically a float).

`Rat` is what falls out of the expressions the OP was working with, specifying you want `Num` is possible.


COBOL used packed decimals, not rationals; fixed precision BCD is quite different from arbitrary precision rationals.


What is the "unicode tapeworm operator"? Google didn't yield much more than this post?


You know the "ç" character? Well, that thing on the bottom is called a cedilla, and in Unicode you can attach a cedilla to anything. Şȩȩ?̧

You can even attach it to the 💩 character. The result looks like this: 💩̧

In Perl 6, you can make anything into an operator. For example, you can write a summation function and assign it to the Σ operator.

The "unicode tapeworm operator" puts these two concepts together.


It is the Unicode Pile of Poo [1] with a Combining Cedilla [2]. In Perl 6, a language that makes Haskell look shy with its operators, you can presumably make this into an operator. You definitely can with the pile of poo itself [3], but I don't know if throwing a combining character in there does anything bad since I've never done it myself.

[1]: http://www.fileformat.info/info/unicode/char/1f4a9/index.htm

[2]: http://www.fileformat.info/info/unicode/char/327/index.htm

[3]: http://blog.mattoates.co.uk/2012/02/perl6-and-fun-with-unico...



Yeah, I would like to know as well. I tried googling, but got the same results as you.


Try this:

perl -C -E 'say "\x{1F4A9}\x{0327}"'


Someone should point his declaration "01 TOTAL PIC S9(4)V9(2)." isn't packed, it's display.


Damn. That's what I get for writing that late at night with a glass of wine in my hand. Plus, I haven't done COBOL for 15 years :)


Yes, it gives very surprising results if you try to do math with output fields delared for display...


I'm very eager for Perl 6 1.0 to come out. I'm even planning on carving out a few weeks to learn it.

I've really poo poo'd the tardiness and vaporware aspects of P6, but I'm starting to get excited again.

Some of the new stuff looks absolutely sublime.


As Larry said during the talk at Fosdem - Lord of the Rings took 14 years to be written too, but it doesn't matter how long something took to write once it's done. That's all in the past.


If you'd like to try some things out now, check this post: http://blogs.perl.org/users/ovid/2014/08/try-rakudobrew-and-...


Of course COBOL, though it has packed decimals, doesn't have general rational numbers. Zetalisp (aka Lisp Machine Lisp) was the first language I know of that had general rationals (ratios of two arbitrary-precision integers).


What are the consequences of using rational numbers by default? I can imagine unexpected bloat when large arrays are in use that you expected to contain native floats but are now a more complex object.


You only get compact storage if you declare the array with a type constraint on the elements, so at that point you start to actively think about the numeric type, and can still convert to floating point if that's what you want.


Crockford's Dec64 proposal has some interesting background on decimal representation: http://dec64.org/


Seems like it's right around the corner. So, when will we have an online course with lessons and exercises for P6? I'd like a set of problems and some quick presentations to work through.

About P6 - I especially like how it becomes more functional-ish and has more consistent notation. Also, the new grammars.

It will probably see more adoption when it is preinstalled in all Linux distros.


> So, when will we have an online course with lessons and exercises for P6?

If you start that project, I'll certainly support you in any way I can.


You can look here for code examples for a given problem: http://rosettacode.org/wiki/Category:Perl_6

We also had an online training about binding C-libs (the first online training that I know of), but it was not recorded. Perhaps we should do so and put it on a youtube channel...


What's inconsistent about the notation of Perl 5?


Another very popular ;) language which supports packed decimals (and decimal64 & decimal128 ) is ABAP.

    data result_float type f.
    result_float = '0.1' + '0.2' - '0.3'.
    write: / result_float.
    >> 5.5511151231257827E-17

    data result_packed type p length 4 decimals 4.
    result_packed = '0.1' + '0.2' - '0.3'.
    write: / result_packed.
    >> 0.0000

    data result_d16 type decfloat16.
    result_d16 = '0.1' + '0.2' - '0.3'.
    write: / result_d16 decimals 16.
    >> 0.0000000000000000

    data result_d34 type decfloat34.
    result_d34 = '0.1' + '0.2' - '0.3'.
    write: / result_d34 decimals 34.
    >> 0.0000000000000000000000000000000000


Perl 5 has packed decimal.


15 years and Perl 6 is still "just around the corner" Does anyone care anymore ?

Perl is largely irrelevant, killed off by the advent of better scripting languages. The inordinate length of time that the incompatible Perl 6 has taken has not earned it any friends either.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: