Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

TIMTOWTDI doesn't mean invent an outlandish approach (usually)

by davido (Archbishop)
on Oct 12, 2003 at 21:06 UTC ( #298713=perlmeditation: print w/ replies, xml ) Need Help??

Read the following as a good natured meditation on the sociology of the Monastery:

Here is the scenario:

Anonymous Monk posts a question, such as:

"How do I empty out a hash?"

Then the answers roll in. There are subtile differences, and some of the answers are entirely valid approaches depending on how the context of the question is intrepreted. Others are rubbish. Please remember, I didn't invent these, I just dug them up with the Perlmonks search engine:

  • %hash = ();
  • undef %hash;
  • %hash = undef;
  • delete @hash{(keys %hash)};
As merlyn poined out, the third solution isn't a solution at all. But eventually things get a little over the top in the context of such a simple question:
  • map { delete $hash{$_} } keys %hash;
  • while (my ($k,$v) = each %hash) { delete $hash{$k} };
  • for (keys %hash) { delete $hash{$_} };
  • delete $hash{$_} for keys %hash;

How about this example:

Newbie asks: How do I find the index of the last element of an array?

  • $lastindex = $#array;
  • scalar(@array) - 1;
  • my $count = -1; map {$count++} @array;
  • $last = $array[-1];

That last example doesn't even do what the question asked, but rather yields the last element, not the index of the last element.

These are very simple examples. They are, however real examples found within real nodes here in the monastery. I chose simple one-liner type examples only to illustrate the point concisely. But I am sure that most of us can think of times when a very simple question, asked in a simple and reasonably well-defined way, resulted in many, many solutions being proposed. Thought provoking answers are good. But most of us can also think of times when many of the proposed solutions ventured down that road of each one wackier and farther from "the Perl way" than its predecessor.

Of course, "The Perl Way" is that there is more than one way to do it. But do we really need to consider the possibility of using, my $len = do { split //, $string; my $counter; $counter++ foreach @_; $counter }; to determine the length of a string just because it's in the spirit of "Another Way To Do It"?

I am all for the diversity of technique that Perl provides the opportunity to explore. But sometimes I find myself wondering, was this response posted because it's a good way to do something, or because the poster found a hot thread and wanted a shot at a few more experience points?

My favorite example of common sense prevailing is the one of merlyn pulling back in the reins when the simple question was asked, "How do I concatenate two strings?". Several answers came in: join "", @strings;, and $string = "this" . "that";, and even  $string = "$first$second"; Then along comes a class act with the best answer of all: "   .   "

Friday golf, obfus, and abused regexp engines can be fun mindbenders. However, it seems like many of the zanier solutions to a simple problem are proposed in what seems to be all seriousness, and it's those sorts of posts that lead me to wonder if this is an XP chase or just plain bad style.

I'm curious what others feel regarding this issue. I'm not looking for "a solution". It's not even a situation in need of a solution. In fact it's not even a situation. It just seems to be human nature to try to one-up the last guy, and often that leads down a chaotic road.

Many will assert that all these examples of many ways to do the same thing are good for the thought process. I don't disagree. But it strikes me as an interesting thing to mull over.

What is the point to this post? My objective is simply to express a meditation. ;)


Dave


"If I had my life to do over again, I'd be a plumber." -- Albert Einstein

Comment on TIMTOWTDI doesn't mean invent an outlandish approach (usually)
Select or Download Code
Re: TIMTOWTDI doesn't mean invent an outlandish approach (usually)
by TVSET (Chaplain) on Oct 12, 2003 at 21:19 UTC
    I'd say that a bunch of responses to a simple question will push a newbie (a proper one) to study the docs and see the difference between the proposed solutions. While doing that, he/she of course will learn a bunch of other stuff. If there was a problem/mistake in the answer, then seeing it corrected by the OP author fullfills the answer.

    Being just few month out of the newbie army myself it's also nice for me to see several answers to simple questions by more experienced monks. This keeps my mind in shape and points out to me other ways to solve simple problems which I didn't yet think about. Emptying of a hash is a good example here. :)

    Update: fixed a stupid typing mistake. :)

Re: TIMTOWTDI doesn't mean invent an outlandish approach (usually)
by idsfa (Vicar) on Oct 12, 2003 at 21:30 UTC

    Dave, I'm sure your last couple of paragraphs cover the majority of the more convoluted responses. A large number are "look how clever I am" posts, either for XP or community recognition. There is a small subset which are really sub-conversations, where the reply is directed more at other posters in the thread than the original question. Like any good party conversation, these can diverge wildly from the starting point. Unfortunately, there is no good way for them to go off into the kitchen.

    The mechanism which seems to be in place to police the zanier posts is, again, XP. The problem is that node reputation is not knowable unless you have already voted on the node or it is a best/worst node. This prevents bias on the part of the voter, but also withholds the critical judgment of PM from the original poster. This reduces the effectiveness of the forum.

    Perhaps if there were just a hint of the regard in which a node is held. If <0 nodes were so flagged in their headers, and highly ++ nodes (say, above the current weekly average) were positively marked, it would give the less informed newbie some insight into the experts' opinion of the answers presented, and not just a byzantine collection of perlish punctuation.


    Remember, when you stare long into the abyss, you could have been home eating ice cream.
      I know that discussions of the voting / reputation process within the monastery are generally viewed with distain, so this isn't a proposal, just another "what if" thought that your followup to my meditation provoked:

      Allow voting to last for 48 hours on a given node. Then close the vote, and expose the reputation for all to see.

      The problem that suggestion creates: After the close of voting do you still allow node edits? You should, in the interest of maintaining the highest quality in the final product of a node. But then how does one who fixed a reputation-sapping problem regain some of the face lost before the node was repaired, if the voting has already closed? The other problem is that nodes that get promoted to celebrity status (promoted to Tutorials) would never reach their full XP potential. And many of us find ourselves upvoting the good nodes years after they were written. Age shouldn't disqualify the good ones from gaining even better reputation.

      The best and most practical solution is to leave it the way it is because we're all used to it, and it's just a fun / trivial aspect to the Monastery anyway. Of course it's still interesting to ponder on the what-if's.


      Dave


      "If I had my life to do over again, I'd be a plumber." -- Albert Einstein
      Perhaps if there were just a hint of the regard in which a node is held.
      There is. You can change the thread display to sort by XP rather than date in your User Settings.

      Makeshifts last the longest.

Re: TIMTOWTDI doesn't mean invent an outlandish approach (usually)
by Anonymous Monk on Oct 12, 2003 at 21:33 UTC

    I think you miss the point of some the wackier answers. Perl is expressive, which allows one to pursue a little creativity. I am not saying that most of the "creative" answers are worth considering as solutions to the task at hand, their worth lies in the creative play that brought them forth and in any creativity they might inspire in others. I seriously doubt anyone is pushing for XP in these cases (and often as not they are posted anonymously anyway). Chaos and creativity are good things in moderation :-)

    Besides, everyone knows that the best way to obtain the length of a string is:

    my $len = 0; $string =~ s/(.)/q|'$len++;$1'|/gimmesomesex;
Re: TIMTOWTDI doesn't mean invent an outlandish approach (usually)
by Juerd (Abbot) on Oct 12, 2003 at 23:14 UTC

    There is more than one way to do it. But not every way is a good one. For example, you mention scalar(@array) - 1 to get the last index. This is not a good way to get the last index. It is a very bad way to get the last index.

    Just like in real language, it isn't only about what you say, but also HOW you express that. scalar(@array) does not mean "the last index plus one" or even "the number that will be the index if you add a new element". It says "the number of elements".

    It would be sort-of okay to use scalar(@array) - 1 if $#array did not exist. But $#array does exist, and it says "the index of the last element in @array".

    $#arrayThe index of the last element
    $#array + 1The index of the last element plus one
    @arrayThe number of elements
    @array - 1The number of elements minus one

    For the same reason, $#array + 1 would be WRONG if you want to get the number of elements.

    Sometimes, unless is better than if. Sometimes unless is wrong and if is right. Sometimes you need to reverse the expressions (open or die versus die unless open) to get the perfect sentence.

    TIMTOWDTI. NYPAGO. (Now You Pick A Good One)

    Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

    P.S. $[ is irrelevant. Yes, it would sort of support my point. But even without $[, using $#array+1 instead of @array, or @array-1 instead of $#array would be wrong when you use code that doesn't express what you meant.

      It does not seem out of place that a quest for canonical form should drive monks. I tend to agree that all ways to express a solution are not equal. Perl is beautiful in its expressiveness, but it does not follow that a solution has value merely because it is excessively clever. Sometimes, other principles should guide. If you need a efficient solution, Perl can provide...but lo' you can get a playful take as well. The context of a problem should guide the monk's post as context guides Perl itself.

      I feel compelled to reveal a guilty secret... I have an irrational dislike of $#array. It seems superfluous.

      Although I use "$array[$#array]" in preference to "$array[@array-1]", I don't enjoy it, and generally prefer to avoid the whole construction. And I always use "$i <= @array" instead of "$i < $#array".

        I hope I will never have to maintain your code. (Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.)

        Anyway... Why the hell would you use $array[$#array]? $array[-1] is so much easier.

        Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

        Although I use "$array[$#array]" in ...

        Have you anything against $array[-1] ??

        Update: Juerd already said it. Must be time to go home...

        ...And I always use "$i <= @array" instead of "$i < $#array"...

        I hope not since they don't mean the same thing unless $[ = 2. However, please realize that $#array is actually:

        $#array = $[ - 1 + @array;

        In other words, if anyone ever sets $[ to anything other than the default 0, not only do they then deserve to be beaten with a rubber mallet but they also break your code. Of course, I'm one of those weirdos who does stuff like:

        my @acceptable = grep { check $array[$_] } ($[..$#array);

        antirice    
        The first rule of Perl club is - use Perl
        The
        ith rule of Perl club is - follow rule i - 1 for i > 1

Re: TIMTOWTDI doesn't mean invent an outlandish approach (usually)
by pg (Canon) on Oct 12, 2003 at 23:21 UTC

    That's life!

    Sometime some people may chose to post an interesting answer (non-traditional) to some simple questions. I would look at those answers interestingly, but probably never use them in real life. However posting those interesting answers is not a crime.

    You can always chose to down vote it, if you don't like it, and think it matters. That's your right, as well as it is the author's right to post it. Good that this is a tech forum, people can only go that far. If you look at some forums about politics, people's view can be way more apart than here and even goes opposite all the time, so... that's life, and we are lucky here.

    Are those posts for XP points, I don't want to second guess the intention. Even if the intention is for XP points, what is wrong about it? If lots of people like it, and it gets lots of points, so... people like it. If lots of poeple down vote it, so...people dislike it.

    The guy you voted against might become your president (potentially this can happen to a little bit less than 50% of the people), so what... that's life, we play with rules. Rules might be wrong, but ...

    The ultimate rule here (or any forum) is to live with people has a different view, taste, etc. Again, luckily this is a tech forum, the space for people to go apart is rather limited than the real world.

    By the way, if you see a post might hurt newbies (usually it does not, hey everyone was/is a newbie, but nobody was/is a dumb. Newbie may not know how to do certain things in Perl, but he/she will judge the answers), post a reply saying "hi, I think this is clever but maybe just for fun."

      The guy you voted against might become your president (potentially this can happen to a little bit less than 50% of the people), so what

      In the US, given the electoral system, this can be true for >50% or the voting population, and I believe that has happened. Hypothetically, with more than two strong candidates, well over 50% of the voting population could vote for a candidate who does not win. Given voter turnout rates, I believe many Presidents have been elected by significatly less than 50% of the eligible population -- a lot of people don't vote.

      The US is messed up.

•Re: TIMTOWTDI doesn't mean invent an outlandish approach (usually)
by merlyn (Sage) on Oct 12, 2003 at 23:27 UTC
      Quoth davido:
      As merlyn poined out, the third solution isn't a solution at all.
      Don't read so fast next time. ;)

      Makeshifts last the longest.

Re: TIMTOWTDI doesn't mean invent an outlandish approach (usually)
by Abigail-II (Bishop) on Oct 12, 2003 at 23:51 UTC
    Then the answers roll in. There are subtile differences, and so many of the answ ers are entirely valid approaches depending on how the context of the question i s intrepreted:
    • %hash = ();
    • undef %hash;
    • %hash = undef;
    • delete @hash{(keys %hash)};
    But eventually things get a little over the top in the context of such a simple question:
    • map { delete $hash{$_} } keys %hash;
    • while (my ($k,$v) = each %hash) { delete $hash{$k} };
    • for (keys %hash) { delete $hash{$_} };
    • delete $hash{$_} for keys %hash;
    I wouldn't call them "entirely valid". Of the first set of answers, one doesn't end up with an empty hash, and one is inefficient. Of the second set of answers, only one is correct, the other three are not guaranteed to work.
    Of course, "The Perl Way" is that there is more than one way to do it. But do we really need to consider the possibility of using, my $len = do { split //, $string; my $counter; $counter++ foreach @_; $counter }; to determine the length of a string just because it's in the spirit of "Another Way To Do It"?
    Oh, I've given answers like that. That is, I've given answers like that if the question is "how do I determine the length of a string". If someone doesn't have the decency to do even the most trivial research in the documentation, I'd consider such a person to be cannon fodder.

    Now, if I were to get paid, I wouldn't have given such a answer, but replied with a question of the form "now, if you were going to look it up in the manual, which guess for a function name would you try first?". But here the questioners don't come with paychecks. The task of the people asking the questions is to keep it interesting for the people answering the questions. That can be done by asking interesting questions, refraining from asking FAQs and trivial questions, or to be at the receiving end of wit and sarcasm.

    Abigail

      Of the first set of answers, one doesn't end up with an empty hash, and one is inefficient. Of the second set of answers, only one is correct, the other three are not guaranteed to work.

      I must be missing something obvious, because I can't quite see why they wouldn't work. But since you say it applies for three of them, it could also be true for the inefficient answer from the first set.(Which I posted without actually looking at the question, in reply to someone posting one of the ones in the second set.) Is this so?

      I'm sure I'll bang my head on the wall once you spill the beans, but what is it that I can't see?

      Makeshifts last the longest.

        The '%hash = undef' is incorrect:
        $ perl -wle '%hash = undef; print scalar %hash' Odd number of elements in hash assignment at -e line 1. Use of uninitialized value in list assignment at -e line 1. 1/8
        It'll create a one element hash, whose key is the empty string, with an undefined value.

        The last three solutions modify the hash while iterating over the keys, which should be a no-no. However, I just read that in the documentation of 'each' that deleting the item most recently returned by 'each()' is safe; this feature seems to have been added (or documented) in 5.6.1.

        Abigail

      or maybe canon fodder?
Re: TIMTOWTDI doesn't mean invent an outlandish approach (usually)
by ambrus (Abbot) on Oct 13, 2003 at 13:14 UTC
    Let me suggest an idea. I think we should accept any too complicated (obfuscated) replies to simple questions, if the monk clearly indicates the reply as such. Then, you can give it ++ if you like the solution, or -- if you don't but the newbie who asked the question would know that (s)he should not take it very seriously.
Re: TIMTOWTDI doesn't mean invent an outlandish approach (usually)
by hardburn (Abbot) on Oct 13, 2003 at 14:09 UTC

    On occasion, a question will spark some wacky part of my brain, so write out "Oh, you can do it this way, too . . . ". I always preface such answers with something along the lines of "Don't use this in real code". I don't do this for XP (in fact, I think most of the downvotes I've received come from such nodes), but just because I thought it was cool and wanted to share it.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://298713]
Approved by broquaint
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2014-07-26 15:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (178 votes), past polls