Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

My habitual errors

by Moron (Curate)
on Apr 04, 2007 at 16:54 UTC ( #608322=perlmeditation: print w/ replies, xml ) Need Help??

I am not sure if this is the right place but ... it looked the nearest category - for example, it certainly ain't poetic!

It's hard to admit your wrong about something. But there are those things you just know you do wrong and have difficulty correcting. In the case of Perl programming, I feel sure there are others out there who recognise the "habitual error" in themselves and have to have a habit of looking for it to compensate e.g..

$hash1{ key1 }{ $hash2 { key2 }
yep it's that second closing bracket after key2 -- now why do I always need the compiler to tell me this on line XXX further down and then have to go look for this ... of course I know me so I know I have to look for something like this. -- or perhaps for something similar with round brackets where the eye deceived just long enough for me to code on and have to find it later.

I wonder what habitual errors others want to share to get it out of their system.

-M

Free your mind

Comment on My habitual errors
Download Code
Re: My habitual errors
by ptum (Priest) on Apr 04, 2007 at 17:12 UTC

    Even after all this time, I still sometimes inadvertently use assignment instead of testing for numeric equality:

    if ($first = $second) { # do something } else { # this code is never executed since assignment to $first always retu +rns true }

    Sigh. It is dumb, but I did it just last week.

    Update: as pointed out by jdporter, in cases where $second evaluates as false, the resulting assignment to $first will also return false. While this rarely happens to me (since I'm usually trying to evaluate numerical equality between non-zero variables), it is an important distinction.

      For comparisons that have a constant I keep that value on the left hand side to avoid accidental assignment. Doesn't work for expressions that use two variables of course.
      if (0 == $n) { } elsif (1 == $n) { }
      # this code is never executed since assignment to $first always returns true

      No; it will be false when $second is false.

      A word spoken in Mind will reach its own level, in the objective world, by its own weight
Re: My habitual errors
by kyle (Abbot) on Apr 04, 2007 at 17:27 UTC

    I opendir/readdir and forget the initial path when I'm using the results.

    opendir my $dh, $dir or die $!; my @files = grep { -f } readdir $dh;

    Then I wonder why nothing matches. Or I collect the list of files and wonder why they all fail to open. In fact, I recently passed this habitual error on to another wisdom-seeker.

      I used to have that same problem, so what I did was create a convention for myself where $dir is the directory, $file is the filename without directory and $path is the two together and make sure that having assigned $path = "$dir/$file", that $dir and $file do not appear further down the same routine (only $path and $dh, the directory handle assigned to $dir)

      -M

      Free your mind

Re: My habitual errors
by dragonchild (Archbishop) on Apr 04, 2007 at 18:32 UTC
    While not a programming item, I had to specially memorize "8 times 7" while in college for a Maths degree. "7 times 8" is 56, obviously, but I could never get it out of my head that "8 times 7" wasn't 48. So, it was like I had a hole in my times tables.

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
      I always go "9 times x is i don't know, so x times 9 is"
        Actually, 9 is easy. 9d (where d is a single digit number) is always two digits, the first being d-1 and the second 10-d (or as I was taught, the second being enough so that the two add up to 9). So 93 is 27 (2 = 3-1, 2+7=9).
Re: My habitual errors (are with open)
by grinder (Bishop) on Apr 04, 2007 at 19:28 UTC

    I get a couple with open. These days, I've expunged globs from my file handling code, and now use lexicals exclusively. That is, I write:

    open my $fh, '<', $file or die...

    as opposed to

    open IN, '<', $file or die ...

    so the mistake I find myself now making regularly is:

    my $fh = open # *pauses*

    and I realise I've messed up and start the line over. Still, at least I catch that as I'm writing it. This is an improvement over the previous situation, where I would regularly write:

    open IN "< $file" or die ...

    And not spot anything was amiss until I ran the code and the compiler complained about syntax errors. Some say that's progress...

    • another intruder with the mooring in the heart of the Perl

      I found that open my $fh doesn't even work for older versions of Perl and have to do something like open \*FH, "blah"; my $fh = \*FH; for old Perls which has a similar effect as the embedded my $fh but isn't quite the same as the erm a bit barer globs you are talking about... But to make code portable between versions without those hardcoded globs, the only way I could think of is something like:
      use FileHandle; my $fh = new FileHandle "< $file"; $fh -> open;
      It just so happens that this way you can put your $fh on the left after all. Unfortunately, for anonymous pipes your point of confusion moves a bit rather than disappears...
      use FileHandle; my $ph = new FileHandle "ps -ef |"; my $pid = $ph -> open; # and you're sort of back where you started.

      -M

      Free your mind

Re: My habitual errors
by graff (Chancellor) on Apr 05, 2007 at 02:43 UTC
    The mistake I seem to make most often -- especially when "patching" or "enhancing" code that was already running -- is forgetting to put the semi-colon at the end of a newly-added line. (Or forgetting the closing slash/bracket on a regex, or...)

    That sort of thing always makes a compile-time error, and the error report always sites a line number somewhere later than the offending line. Drives me up a wall -- I should be habituated to typing ";" before the "return" key or whatever, but I still forget...

    Since I use emacs, a forgetten close-bracket usually causes unexpected behavior with auto-indenting, so I catch it while editing, but the forgotten slash or semi-colon seems to squeak through fairly often.

      Me too!
      It can then be very difficult to find, especially if you have been coding for a long time and your eyes are tired.
      My favourite gaff is to mix curly and round braces.
      Gavin
        My favourite gaff is to mix curly and round braces.

        That's one of mine as well. Fortunately xemacs has an option that high-lights the starting character of the clause that ends with the current curly or round brace -- green if the starting character matches, red if it does not.

Re: My habitual errors
by hangon (Deacon) on Apr 05, 2007 at 08:26 UTC

    I have a few, but this one turns out to be a huge time waster. The habitual part is that for some reason this error is completely invisible to me until my eyes are bloodshot and I've banged my head on the keyboard several times.

    my %hash = (abc => 1, def => 2); $key = 'abc'; $value = $hash{key}; # now try to use $value for something

    Maybe confession wil help.

      Very nasty! I was typing it out in vi in disbelief with the idea of running it through perl -d, and only when just about to type the actual mistake could my brain focus enough to spot it. And I suppose even though use strict would force the corrective focus in this particular example, it wouldn't trap every case where that error could be made.

      -M

      Free your mind

      Try using lock_keys from Hash::Util. It's like strict refs for hash keys.


      TGI says moo

Re: My habitual errors
by gloryhack (Deacon) on Apr 05, 2007 at 14:12 UTC
    My foible, a silly little simple thing it is too, is that I can easily cross my wires when dealing with HoH's. If I have:

    my %families = ( desilu => {ricky => 'lucy', fred => 'ethel', }, bedrock => {fred => 'wilma', barney => 'betty', }, );

    ... every now and then I go insane and try to dive in with:

    my $whiner = $families -> {desilu} -> {ricky};

    It's not really a habit, but if I do it once in a project, I do it many times. So I'm very good friends with Data::Dumper::Simple.

Re: My habitual errors
by Old_Gray_Bear (Bishop) on Apr 05, 2007 at 15:07 UTC
    In addition to the usual (is that a '(' or a '{'}, my "favorites" are:
    #! /user/local/bin/perl use strict; use warnongs;
    I have actually threatened to set up a sym-link for  /user -> /usr and portability be hanged. Fortunately the other error is egregious and the Compiler let me know fast. (May be I can set up a vin macro for that....)

    ----
    I Go Back to Sleep, Now.

    OGB

      If you are in the habit of doing a perl -c before trying to run it, you could alias perl just locally for your username, detect the perl -c and conditionally do your personal error checking and then run the real perl + whatever args after that.

      -M

      Free your mind

Re: My habitual errors
by adrianh (Chancellor) on Apr 07, 2007 at 20:48 UTC
    I wonder what habitual errors others want to share to get it out of their system.

    I wouldn't say it was habitual - but I still occasionally write $something{ shift } and spend some time being confused when it doesn't DWIM.

Re: My habitual errors
by liverpole (Monsignor) on Apr 15, 2007 at 15:13 UTC
    Hi moron,

    That's a very entertaining question!  The reason it took me a while to answer is was that I couldn't remember the overriding mistake that I make, out of the many that I make all the time.  I knew there was something, but I just couldn't put my finger on it.

    Then I remembered ... the hands-down winner for me is putting semi-colons after values in a declared hash, instead of commas.

    That is, I like to write long data structures in this format:

    my $p_employee = { 'alice' => { 'salary' => 75000, 'hired' => 1176649545, 'manager' => 'bob', }, 'bob' => { 'salary' => 82000, 'hired' => 1145113545, 'manager' => 'carol', }, 'carol' => { 'salary' => 96000, 'hired' => 1145113545, 'manager' => 'thomas', }, };

    But invariably I end up putting semi-colons at the end of one or more lines -- for example:

    my $p_employee = { 'alice' => { 'salary' => 75000, 'hired' => 1176649545, 'manager' => 'bob', }; 'bob' => { 'salary' => 82000, 'hired' => 1145113545, 'manager' => 'carol', }; 'carol' => { 'salary' => 96000, 'hired' => 1145113545, 'manager' => 'thomas', }, };

    It also seems to happen with a frequency in direct proportion to the complexity of the data structure.  I'm pretty sure this has bitten me more than any other single class of error.


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: My habitual errors
by shmem (Canon) on Apr 15, 2007 at 15:52 UTC
    Mine is forgetting semicolons after inline blocks
    $foo = sub { my $var = shift; ... } for my $bar(@quux) { ... }

    since blocks which aren't inline don't need semicolons.

    Happens often while making named subroutines into anonymous ones, and also with do blocks. Often I get bitten for omitting a semicolon on the last line in a block:

    sub foo { my $ret = bar($_[0]) * quux($_[1]) }

    Later, I add more statements

    sub foo { my $ret = bar($_[0]) * quux($_[1]) $ret *= 1024 }

    bummer...!

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: My habitual errors
by naikonta (Curate) on Apr 15, 2007 at 16:18 UTC
    • Forgetting the ";" and "," where they're due.
    • Typing ":" instead of ";"

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Re: My habitual errors
by ambrus (Abbot) on Apr 15, 2007 at 18:21 UTC

    An error I often make is forgetting semicolons. I do that most often after debugging print/printf/warn statements, or long statements, like ones that end with the closing brace of an anonymous sub. This, fortunately, causes a syntax error pointing to the right place in the majority of cases.

    The other error I often do is failing to return the right value from a subroutine. The value is computed all right, only I forget to add the last statement that returns it after writing the body.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2014-08-31 00:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls