Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Learning perlisms leads to experience, wisdom and discoveries that whitespace & idioms are lazy

by Mr. Muskrat (Canon)
on Dec 23, 2004 at 07:08 UTC ( #417014=perlmeditation: print w/replies, xml ) Need Help??

I have been working as a programmer (among other things) for the past several years. In this time, I have picked up some knowledge that I would like to pass along in the hope that you will not make the same mistakes that I and those around me have already made.

Learn from the wisdom (and lack thereof too) of those around you who have more experience programming in Perl.

Notice that I did not say those who are older than you, have more seniority or hold a supervisory position over you. In some cultures this is a hard concept to grasp. Give that "kid" a chance, she might teach you a thing or two about proper programming.

As for the "lack thereof", you will find out eventually that some people just do not get it even after programming in Perl (or any other profession for that matter) for many years. Learn from their mistakes as well as your own.

There is a time and place for trying out your recent Perl discoveries.

Learning is a good thing especially when you are learning more about Perl. You should practice what you have learned as often as you can so that you retain the knowledge.

That said, code that is destined to be released into production is not the place to practice your new found knowledge of hash slices.

Perl idioms are our friends.

Why say

# take the values in @array and use them as a hash slice to make all o +f the values 1 @hash{@array} = (1) x @array;
# take the values in @array and use them as keys in %hash, incrementin +g the values associated with said keys by one for (@array) { $hash{$_}++; }
$hash{$_}++ for (@array); # same as above only with the for at the end
are more widely understood? (See foreach loops.)

Whitespace is too.

This (shamelessly stolen and slightly modified) line of code

is just dying for some whitespace (unless of course you really are Writing highly obfuscated code in Perl).
print map { sprintf '&#%d;', $_ } unpack 'C*', $string;
or even
print map { sprintf '&#%d;', $_ } unpack 'C*', $string;

Double (or even triple) check your data.

I cannot tell you how many times some new code was added that introduced a bug or that I have received a bug fix that was not needed simply because the person was using invalid data.

Remember what I said about idioms earlier? A programmer had introduced a bug when they tried to use the hash slice instead of the idiom. The data (as output by Data::Dumper) looked something like this:

$VAR1 = { 'YZ0' => undef, 'MNO' => undef, 'ABC' => '111111111', 'DEF' => undef, 'STU' => undef, 'VWX' => undef, 'JKL' => undef, 'PQR' => undef, 'GHI' => undef };
When it should have looked like this:
$VAR1 = { 'YZ0' => 1, 'MNO' => 1, 'ABC' => 1, 'DEF' => 1, 'STU' => 1, 'VWX' => 1, 'JKL' => 1, 'PQR' => 1, 'GHI' => 1 };
What bug caused it?
@hash{@array} = (1 x @array);
Note that the closing parenthesis doesn't follow the 1 but @array. The programmer did not check the data that was created. He simply assumed it was correct (which leads me to my next point).

Do not assume anything.

Throughout our lives we make assumptions about all sorts of things like the weather ("I better take the umbrella. Based on the look of those clouds it's going to rain."), traffic patterns ("It's Friday. I better not take the highway or I'll be late for work!"), et cetera. Sometimes we are right and sometimes we are wrong.

When dealing with code and data, assumptions usually mean mistakes. You have the code and the data so why assume anything? (Because most people tend to be lazy and not the virtuous kind either!)

Be lazy but do not take shortcuts.

Do not take the easy way out by assuming your data or code is correct. Do not skip testing things because you would rather be doing some thing else. Shortcuts lead to mistakes which lead to more time spent debugging.

Be lazy in a good way. Make use of the tools at hand (like CPAN) to save coding time and effort. Do it right the first time even if it takes a little longer now. You will save more time in the long run.

Get a "code bear".

I am not sure where I first heard about this technique but it seems to work for everyone. Pick something other than a real person and thoroughly explain the problem at hand. Your "code bear" can be a stuffed animal, a mirror, your pet gerbil or even a picture of Nikki Cox. (You know who you are! ;-) For example, my "code bear" is a stuffed animal that my wife gave me for Valentine's day this year.

The idea is a simple one: completely express your thoughts out loud. Explain the problem with as much detail as you would when speaking with a peer. In most cases, the act of putting the problem into words will get your brain cranking enough to solve the problem without wasting the time of an already overworked (and usually underpaid) co-worker. If you have not figured it out by this point then by all means discuss it with someone who can help.

Use every available resource.

By now some of you are probably saying to yourself, "This guy has put way too many links in this node. He must be nuts!" Normally I would agree with you but not this time. I put them in here to make a point.

How many times have you heard someone say something like this? "I checked my Perl pocket guide but I couldn't find what I was looking for." or "I thought that you could do X with Perl but I can't get it to work. Can you help?"

There is a wealth of information that is only a few clicks and keystrokes away. You do not have to limit yourself to just PerlMonks either. Check out,, (this last one has links to just about every Perl resource you could possibly need), et cetera.

No need to limit yourself to online resources either! Go out and buy some books. Go to the library and check out some books too.

This is not an exhaustive listing by any means but some of the things that I have encountered most often. What are some of the best practices that you have learned?


Many thanks to ybiC! He spent a considerable amount of time reading this and offering feedback on how to make it better. I would also like to thank the rest of the reviewers (DigitalKitty and mojotoad spring to mind but I'm sure there were others).

Update: I'm in the process of updating the links that the ones that are pretty much random actually point to a relevant place.

  • Comment on Learning perlisms leads to experience, wisdom and discoveries that whitespace & idioms are lazy
  • Select or Download Code

Replies are listed 'Best First'.
Re: Learning perlisms leads to experience, wisdom and discoveries that whitespace & idioms are lazy
by diotalevi (Canon) on Dec 23, 2004 at 07:59 UTC

    I hope that no one reads your node and gets the idea that hash slices are somehow exotic. They aren't. Substituting in a loop is baby perl and while there there are places where that is appropriate and good, there are plenty of places choosing slower but simpler for newbies isn't the right decision. Personally, I'd never consider the looped version "correct" unless there was a really good reason to use the other version.

    Also, did you mean to link to anything in particular with each of your [linked] nodes? Maybe you meant to make them [google:// links]?

      By the way, do you know why the hash slice method is faster than looping? I measured and looks like it really is and by a significant amount of up to 25%. Seems strange.

        Hash slicing does the assignment loop in C; explicitly looping does it in Perl.

      I second dios question, what are all those internal links for? (It's distracting me from actually reading the content)


        Maybe he just meant to underline certain keywords? Putting brackets around something is easier than adding <u></u> or <b></b>, but the links are very distracting. I kept hovering my mouse over them to see what they link to, but almost all of the links are just the word itself, which leads me to the preceding conclusion.

Re: Learning perlisms leads to experience, wisdom and discoveries that whitespace & idioms are lazy
by rir (Vicar) on Dec 23, 2004 at 14:58 UTC
    Mr. Muskrat, you raise some interesting issues.

    Learning from the mistakes of the less experienced is an interesting tease. I would be happy to hear some expansion of this idea. I've always been one to read things that are beneath my level because I might pick up some stray bit or previously missed fundamental. I don't feel that I've applied the concept so well to people.

    To learn from the mistakes of people who just don't get it seems to me inefficient; that one may learn from the bad code and other artifacts they produce seems more efficient but still difficult. Can you expand? If one can effectively learn from the clueless there are vast territories in learning for me to explore.

    I will put newly learned constructs into production code. This works for me; I suspect that I am more ponderously slow and careful than the average coder.

    Idioms are idioms, they must be learned.

    Checking your data, not assuming anything, and avoiding shortcuts are all points I agree with. I would merge those all together into a test test test statement. And one key to good testing is to build tests into the build system.

    I agree entirely with your code bear comments. Also one may consider that many people do not listen as well as a inanimate object; I take that as a challenge to be a better listener.

    Use every available resource is too simplistic. The wasted time I spent following the useless links in your node support my point. The quality of a resource is important. One can only deal with so many resources at a time. Hopefully, one absorbs resources and continues to find others to absorb.

    Be well.

Re: Learning perlisms leads to experience, wisdom and discoveries that whitespace & idioms are lazy
by Mr. Muskrat (Canon) on Dec 23, 2004 at 16:47 UTC

    Rather than reply to each node and basically say the same thing, I'll just do it here.

    The point of the first section is to pay attention to those who have more experience programming with Perl and try not to follow in the footsteps of those whose will never learn Perl no matter how long they use it. Judge a programmer by the work they produce not their resume. That new "kid" may already be a wizard. The senior programmer that acts as your supervisor may or may not have earned the position. If you find a wizard, pick up some pointers along the way. The eternal Perl user keeps making the same mistakes. If you learn from your (or their) mistakes the first time, you can move on to new mistakes and a new understanding.

    The way that hash slices were treated seemed to confuse more than help. I was just using them as a continuing theme that started with this comment "That said, code that is destined to be released into production is not the place to practice your new found knowledge of hash slices." Perhaps I should have stressed the "new found knowledge" a bit more. I'm not saying that @hash{@array} = (1) x @array; should not be used for this sort of thing. What I am trying to say is if you don't know something every well, fall back on the idioms that you do know. It may have been a bit clearer if I had moved "Double (or even triple) check your data" right after that section since it picks up the hash slice theme by using the misremembered @hash{@array} = (1 x @array); (which just creates a string of ones as the value for the key created by the first element of the array).

    The links. It looks like that idea didn't work out either otherwise you wouldn't have mentioned them. If you read the last section "Use every available resource" (you didn't read it because you were distracted by all the links, right?), you'll find "There is a wealth of information that is only a few clicks and keystrokes away." Based on the feedback, I really did go overboard with them and I apologize.

    Update: Split the last sentence of the first paragraph into two sentences to clarify the meaning.

      Re links: Yes, I did read that bit, which is why I clicked on several links, hoping you'd set them cleverly to actually link to corresponding information.. However most just send me to perlmonks' multiple hits page, but no relevant information. (One at least ends up pointing at just this article and it's replies.. intended?) - It would have been neat if the links did actually point somewhere useful..


Re: Learning perlisms leads to experience, wisdom and discoveries that whitespace & idioms are lazy
by itub (Priest) on Dec 23, 2004 at 14:46 UTC
    Hash slices are an idiom too. Where do you draw the line? Some people will say that grep and map are exotic; some people will say that eval is exotic; some people will say that x, .. and ? : are exotic.
Re: Learning perlisms leads to experience, wisdom and discoveries that whitespace & idioms are lazy
by techra (Pilgrim) on Dec 27, 2004 at 15:41 UTC

    This reminds me of a quote I once found that is basically my motto as a programmer:

    "A good programmer looks both ways before crossing a one way street."

    No assumptions.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://417014]
Approved by Zaxo
Front-paged by Old_Gray_Bear
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2022-12-05 00:50 GMT
Find Nodes?
    Voting Booth?

    No recent polls found