Hacker News new | past | comments | ask | show | jobs | submit login

> for $line (@array) {

> print $line unless $seen{$line}++;

> }

The impulse to golf is strong …. How about

    $seen{$_}++ or print for @array

?



It's very clever.

That's why I always use the non-clever version for my code, except with foreach instead of for, just so that it reads like English.

Clever is fun, though. I do understand the temptation. I admit to having done crazy stuff like turning a JAPH into a vulnerability scanner (in retrospect, the "fork until there are 256 of you and scan an entire subnet at the same time" thing wasn't that great). But I usually find myself wanting to come back to the code and know what I was thinking.

Being too clever makes that difficult.


Golfing aside (I don't golf), I guess this pattern struck me as being natural and not really trying to be clever.

Used in small doses and when you need something quick and dirty, it has been immensely useful, much like vlookup() in Excel.


Depends on which pattern you're talking about. I was talking about inverting everything and using the magic of $_ everywhere.

If you mean just the idea of using a hash to mark things you've seen before, though, that is very, very useful. But I would write it as:

foreach $item (@list) { # Print every item in the list skipping duplicate items. print $item unless $seen{$item}++; }

Because then I don't have to think about what's happening with all the magic $_ variables Perl is tossing around. Sure, they're convenient. And I do use them some of the time. But when things break, I'm usually glad that I was explicit about what I was doing rather than relying on Perl's magic to know what I intended to do.

Maybe that's why I like Perl so much? I tend to code in as strictly disciplined a manner as I can manage, so I don't end up regretting it later.


The golf(ish) answer is by JadeNB. My original code is exactly the same as yours =)

But more importantly, I have not seen anyone post equivalent Python or Ruby code.


There was no comment and you used for instead of foreach, but that's just a nit. I did lose track of which person I was replying to :)

You're right that the overall pattern is VERY useful.


Guess no Rubyists or Pythonistas want to step up to the plate. =)




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

Search: