Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Stupid mistakes I repeatedly make

by brian_d_foy (Abbot)
on Mar 27, 2005 at 07:07 UTC ( #442597=perlmeditation: print w/ replies, xml ) Need Help??

I was teaching Perl again this week, and as part of the class I usually end up doing some sort of live programming demonstration. I started doing that around the year 2000, and it is as dangerous now as it was then.

I figured that too many students thought that I wrote code by starting at the top of the file and typed until I got the end of the file. Some people may come up with the entire program in their heads and type it out, but I generally program an outline, then circle around each main part as I add new features. If I don't do that, I start with one piece then program from the inside out.

If I do this in front of a bunch of people by having my typing projected onto a large screen, everyone gets to see all the stupid mistakes and typos that I make. It's generally good that they get to see that so they realize that although I'm exuding confidence in just about everything I tell them, I'm also a regular guy who makes all the same mistakes everyone else does. An expert is simply someone who has made every mistake, after all.

This isn't a list of problems with Perl, complaints about Perl, pleas for help, or anything else that merits attention. It's just documentation of my sometimes stupidity. It's the little details that cause more problems then program flow or big design issues. Go figure.

s/// at the end of a map()
No matter how often I remind myself that s/// does not return the string, my fingers still type the code as if it does. What do I really get? A list of the return values of s///, which are either 1s or empty strings.
my @array = map { s/regex/replacement/ } @input;
my %hash = { }; or my $hash = ( );
Once I got use to anonymous references, I started using them more than the named variables. If I have a data structure, I'm probably going to pass it around so I might as well start its life as a reference. A mistake that I've been making a lot this month is using the wrong constructor: the anonymous hash constructor when I want a named hash, and the list constructor when I want an anonymous hash. It's no one's fault but my own, really, but I still do it frequently, it seems.

print Dumper( $hash );
Can you see what's wrong with that? You'll find out quickly when you try to run that program: I didn't use Data::Dumper. Sometimes I wish that Perl was smart enough to figure that out and load the package for me. My favorite debugger is still print, and perl has to remind me to load Data::Dumper on the first go around for a new script.

( $year, $month, $day ) = ( localtime )[3,4,5];
No matter how many times I look it up, and how many times I use it, in moments of weakness I get it backwards. It's not that I think don't sync the left and right hand sides, but that I have it in my head that the year comes first. It's dumb that I think that because the size of the interval gets larger with higher indices.

my( $n, $m, $o ) = shift;
I start off with one variable and use shift to assign it a value, but then I need more variables, so I add them on the left-hand side, but I don't update the right-hand side. Sure it's dumb, but that doesn't mean that I don't do it.

--
brian d foy <brian@stonehenge.com>

Comment on Stupid mistakes I repeatedly make
Select or Download Code
Re: Stupid mistakes I repeatedly make
by demerphq (Chancellor) on Mar 27, 2005 at 09:18 UTC

    For the record the only one here that I dont do myself regularly is the hash initialization. IMO you may find that finding a better font to code in will remove this one from happening. Too many fixed size fonts have really crappy {} symbols that look far too similar to (). The point should stand out damnit!

    ---
    demerphq

      ... and the older my eyes get, the worse the problem becomes.

      The various language variants of WST_ are _less_nasty_ than some (for 'doze), though they still leave much to be desired. Even better, IMO, is the proggy.... fontset, with many plusses, including slashed or dotted zeroes, readily distinguishable { and ( (with bold variants, which help me lot), etc.

      Had semi-seriously considered building my own, with special attention to diffs between curly and paren, semi and colon, etc...
      but good sense (as in limited graphic talents and knowledge so eone else has already done it well) has so far prevailed.

        Yeah I credit proggy fonts with the elimination of this type of error for my daya to day to usage. They are much better than the courier variants.

        ---
        demerphq

      I don't do it because I can't tell the difference between the glyphs on the screen: I do it because I'm stupid. I have ProFont in BBEdit and whatever vim normally uses, and it's bery clear what is what. :)

      --
      brian d foy <brian@stonehenge.com>
        That very versus bery is more common in North Portugal. People can't tell when we are speaking v or b. And more, I don't know why keyboards still habe then near each other.

        Alberto Simões

Re: Stupid mistakes I repeatedly make
by matthewb (Deacon) on Mar 27, 2005 at 09:24 UTC

    ++ nice to know you're human.

    I have a personal bug that typically irritates me about twice a week. It is that, even if it is a value in some hash, my brain interprets a method call as a something that should end with a semicolon. Thus, I frequently type something like:

    my $hash = { key1 => 'scalar value', key2 => [ qw( its an array ) ], key3 => Some::Package->method( $args, $go, $here, ); # <-- oops! };

    This is somewhat insidious because it doesn't break emacs' syntax highlighting and perl -c /path/to/script reports the error as being on the next line. Ho hum, confession is good for the soul.


    MB

      Ah, yes, I've done that one quite a bit too, and it's not just in a hash: I get it for list creation that goes into a normal array (or even into a list operator). I think this one is just finger memory: a semicolon just automatically comes after a closing paren.

      --
      brian d foy <brian@stonehenge.com>
Re: Stupid mistakes I repeatedly make
by rg0now (Chaplain) on Mar 27, 2005 at 10:04 UTC
    No matter how often I remind myself that s/// does not return the string, my fingers still type the code as if it does.

    This problem becomes even more notorious, when you have to use PHP once in a while, and you get used to the familiar behavior of preg_replace. preg_replace does exactly what you wrote, that is, it returns the replaced string. I know, it has come up before many times here, but for me that PHP-ish behavior is much more natural. This does not generalize to PHP itself, though...

    rg0now

      Just out of off-topic curiousity - how does PHP let you know how many things were replaced?

      Being right, does not endow the right to be rude; politeness costs nothing.
      Being unknowing, is not the same as being stupid.
      Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
      Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

        Now, you caught me. After many years hacking PHP, I have never ever needed to know the exact number of times the replacement succeeded. In the use cases I meet (and this applies to Perl as well), the task is always to do the replacement, if it can be done, and leave everything as it was otherwise.

        As of PHP 4, I can't really think of any straightforward solutions. Maybe, I would use a separate round of pattern matching first to derive the number, if I had to do such thing, but I am sure that other monks more familiar with this aspect of PHP will correct me, if I am wrong.

        rg0now

        Just to follow this thread off-topic ... how often does it matter? I can't even think of any time where I cared how many items were replaced with s///. And it's almost never when I don't care about the resultant string. So, yes, I'd agree that PHP's method is as flexible as Perl's, but I would suggest that the s operator is not Huffman-coded properly. The thing that we do most often (care about the resultant string) is the most work. Even if the difference is minor (an extra set of parens), Larry seems to talk a lot about "natural language" for perl 6, and I'd suggest that the current syntax is less natural. If, for example, s/// returned the resultant string in scalar context and the list of substitutions in list context, you could get the number of substitutions with my $num = @{[s/$re/foo/g]}; (although that syntax is probably not so ugly in perl 6 either). Given the rareness of its use (if my experience is any indication, or even in the same ballpark as reality in general), I think this would make more sense.

        I seem to recall that perl6 is supposed to solve all of this, so not only is this thread off-topic, but probably moot anyway ;-)

        Here's one way to do it in PHP. There are possibly better ways.

        #!/usr/bin/php -q <?php error_reporting(E_ALL); $data = array("one", "foo", "two", "foo", "three", "foo", "four", "foo", "foo"); $changed = 0; $new = preg_replace_callback("/foo/", create_function( '', '$GLOBALS{"changed"}++; return "bar";' ), $data); print_r($new); print "We changed $changed items\n"; ?>

        This prints

        Array ( [0] => one [1] => bar [2] => two [3] => bar [4] => three [5] => bar [6] => four [7] => bar [8] => bar ) We changed 5 items

        I hope this helps satisfy your curiosity

      This one, I managed to avoid. I did it once early in my Perl life, and learned the mantra before the bad habit set in:

      s/something/else/ for @list;

      But, how do you accomplish the same thing with map, and does it make any difference?

      Anima Legato
      .oO all things connect through the motion of the mind

        s/something/else/ for @list;

        But, how do you accomplish the same thing with map, and does it make any difference?

        my @new_list = map { ( my $tmp = $_) =~ s/.../.../; $tmp  } @list;

        It's useful only for those times when you don't want to corrupt the original list, for whatever reason

        You could probably also do:

        @list = map { s/.../.../; $_ } @list;

        but you'd take a performance hit for building the list in memory, I would think. (I haven't benchmarked it).

        Update: Anonymous makes a good point -- faster not to assign it back to itself. (but there is still a performance hit as compared to for/foreach, so just use one of those, and only use map if you don't want to corrupt the original).

Re: Stupid mistakes I repeatedly make
by jplindstrom (Monsignor) on Mar 27, 2005 at 13:09 UTC
    When initializing a hashref, I sometimes mistakenly use = instead of => when going back to add new item, especially (for some reason) when they are deeply nested.

    my $hr = { foo => "bar", bar = "baz", #boom };

    /J

Re: Stupid mistakes I repeatedly make
by tlm (Prior) on Mar 27, 2005 at 14:28 UTC

    OK, here are mine.

    open OUT ">$output_file" or die $!;
    or its companion:
    print OUT, "foo bar baz\n";
    Although I've noticed a certain improvement with the first one of these ever since I started using the "extended form" of open and lexical handles:
    open my $out, '>', $output_file or die $!;

    Here's another one (I've already given up all hope with this one):

    push @foo = 'bar'; # aaaaargh!!!
    Why? WHY???

    A whole raft of them all have to do with precedence mixups:

    my $foo = $bar or $baz; print "You have $foo foo" . $foo==1?'':'s' . ":\n"; my @frobozz = map foo($_) or bar($_), @baz;
    (That's three precedence bugs, one per line. At least.)

    Correction: Make that 4.

    And the forgotten semi-colons (2 bugs, at least):

    eval { what() if $i == do { this() }; } die $@ if $@; my $coderef = sub { my $name = shift; return "don't worry $name, be happy\n"; } print $coderef->('Pustular');
    ...though my editor usually helps me with these.

    And the meanest of them all:

    eval { "require $foo; 1" } or die "Where's $foo?\n"; print $foo->happiness();
    Ouch.

    There are many more that routinely chomp my monkly butt, but reliving all these bugs at once is beginning to give me the shakes...

    the lowliest monk

Re: Stupid mistakes I repeatedly make
by itub (Priest) on Mar 27, 2005 at 15:33 UTC
    I've made most of those errors at least once, but the most common for me is the last one (my( $n, $m, $o ) = shift;). By now I've tried to standardized on my ($n) = @_ even for one parameter, but when I change code that has shifts I often forget.

    It would be interesting to set up a poll titled "The stupid mistake that I make most often" with some of the errors discussed in this thread.

      I used to do the my ($n, $m, $o) = shift so often that I vigorously enforce always using @_ now in my code. Because without fail the one time I use shift, I end up adding a variable later.

      Plus I get really annoyed with all the extra typing I have to do to convert it from one format to the other. I suppose I should create an emacs macro to do that for me...Its good to know that laziness does indeed support good habits. ;-)

Re: Stupid mistakes I repeatedly make
by gam3 (Curate) on Mar 27, 2005 at 16:07 UTC
    This is simular to the s/// and gets me all the time.
    @chomped = map {chomp} @_;
    -- gam3
    A picture is worth a thousand words, but takes 200K.

      Then toss map and open up your life to the "listable" form of chomp:

      @chomped = @_; chomp @chomped; # yum-yum

      the lowliest monk

        Or even better: chomp (my @chomped = @_);
        --kap
Re: Stupid mistakes I repeatedly make
by tilly (Archbishop) on Mar 27, 2005 at 16:10 UTC
    I don't do most of yours. (The shift one I do, but not the others.) However a big favorite of mine is forgetting when I need to type $foo{bar} vs $foo->{bar}. But hey, that's what I use strict for, right?
      Is it not rather that you can't easily tell from context whether foo is a hash or a hashref?

      /J

        Is it not rather that you can't easily tell from context whether foo is a hash or a hashref?
        It's not paying attention to context. Last time I did that, I passed a reference to a named hash to a function, e.g., foo_function(\%hash), then in the function started using the argument as a hash instead of a hash reference, and inconsistently at that. And then going back to the calling function, and adding code that assumed the hash was a reference. TGFS (Thank Go(o?)d(ness)? for strict :)
        Oh I can tell.

        It is just that while coding, my fingers apparently can't (consistently at least).

        This may have something to do with the fact that I use hashrefs a lot like I use hashes. Or the fact that I don't care because strict catches it so quickly, so I don't pay close enough attention to get it right.

Re: Stupid mistakes I repeatedly make
by nobull (Friar) on Mar 27, 2005 at 17:02 UTC
    my @array = map { s/regex/replacement/ } @input;

    That's why I created the trivial function apply() that later found a home in Tassilo von Parseval's List::MoreUtils.

    use List::MoreUtils qw(apply); my @array = apply { s/regex/replacement/ } @input;
      Also implemented in Algorithm::Loops 'Filter', though it gives different results in scalar context.

      Caution: Contents may have been coded under pressure.
Re: Stupid mistakes I repeatedly make
by Corion (Pope) on Mar 27, 2005 at 17:07 UTC

    I some times fall for the my ($self, $bar, $baz) = shift; bug, but there is another bug that catches me, especially when I start to consciously think about it instead of letting my fingers interpret my commands:

    my $foo = 'bar'; $foo ~= s/a/ee/;

    Of course, this is the reversed regex operator (which doesn't exist), and Perl sees this as a syntax error. ambrus taught me a good mnenonic - the negated comparison for the regex binding operator is !~, which has the same order as !=, and thus, the regex binding operator must be =~.

    In a certain way this confusion when thinking about what my fingers should be doing reminds me of the problem that octopodes have when coordinating their arms, which, seemingly, they never do - they just send commands to them and then verify the behaviour by optical inspection.

      Heh, I used to do the same thing occasionally as a newbie, and overcame it the exact same way :)

      /J

      ambrus taught me a good mnenonic - the negated comparison for the regex binding operator is !~, which has the same order as !=, and thus, the regex binding operator must be =~.

      I use the same mnemonic but word it a bit differently: I tend to translate $a == $b to "a is b", so I translate $a =~ /Pattern/ as "a is like Pattern", and since ! is traditionally "not" I translate $a !~/Pattern/ as "a not like Pattern".

      Thus the "=~" operator to me is the "is like" operator and the "!~" operator is the "not like" operator.

      ---
      demerphq

        Teaching is a great way to get paid to say something over and over again so you don't ever forget it. Sadly, there are only four days in our Learning Perl course, and we even say in the first fifteen minutes that we can't teach everything in a week. :)

        --
        brian d foy <brian@stonehenge.com>
Re: Stupid mistakes I repeatedly make
by friedo (Prior) on Mar 27, 2005 at 18:18 UTC
    my( $n, $m, $o ) = shift;

    I used to do this one all the time also. I just got in the habit of not using shift. Instead I'd do:

    my ( $n ) = @_;

    Works just as well and is nearly impossible to screw up if you need more variables.

      Works just as well . . .

      But, it's not identical. The first consumes elements from @_ and the second doesn't. This means that functions which are iterating over @_ (for whatever reason) will not work with this refactoring.

      Being right, does not endow the right to be rude; politeness costs nothing.
      Being unknowing, is not the same as being stupid.
      Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
      Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

        I usually avoid shift unless I specifically need that array reduction behavior. In the context of parameter processing this is usually in OO-land when one method needs to call another with the same arguments it was given, e.g.

        sub method1 { my $self = shift; ... maybe do some stuff ... $self->method2(@_); ... maybe do some more stuff ... return $something; } # or even more simply sub method2 { shift->method3(@_) }

        Otherwise I always my($c,...) = @_;

        --DrWhy

        "If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."

        There's always
        $_= shift for my ($i, $j, $k);
        which is pretty foolproof, though unconventional (read "ugly").

        Caution: Contents may have been coded under pressure.
      I'm the other way. I don't like things being in @_ unless they need to be passed down. In addition, in terms of english, I prefer the paralel structure of using shift multiple times. You'll often see me write:
      my($n,$m,$o) = (shift,shift,shift);
      which I think is rather elegant... in addition, having to add another shift when I add another variable of input (if I do) generally makes me think over the results and implementation of adding one, which is good :)
Re: Stupid mistakes I repeatedly make
by ForgotPasswordAgain (Deacon) on Mar 27, 2005 at 20:20 UTC
    my %hash = { };

    I found this used several times in code we'd hired some contractors to do. The infuriating thing was that it actually seems to work... so I ended up looking like a weenie when complaining about the quality of the code.

      The infuriating thing was that it actually seems to work

      Sure, it "works", but it's certainly not right:

      $ perl -MData::Dumper -we 'my %hash = {}; print Dumper \%hash' Reference found where even-sized list expected at -e line 1. $VAR1 = { 'HASH(0x814cc20)' => undef };

      It generates a warning and adds a useless entry to the hash. I can't imagine that's what the contractors wanted to do. :-)

      my %hash = { };
      I found this used several times in code we'd hired some contractors to do. The infuriating thing was that it actually seems to work...

      You need to start using the -w flag more, my friend (that or use warnings). If you had, then perl would have warned you:

      % perl -we 'my %hash = { }' Reference found where even-sized list expected at -e line 1.

      the lowliest monk

Re: Stupid mistakes I repeatedly make
by dna (Beadle) on Mar 27, 2005 at 21:37 UTC

    use module qw/something else/g

    Considering how far the 'g'- and ';'-buttons are from eachother, it's amazing that I can make the same mistake every time.

Re: Stupid mistakes I repeatedly make
by sh1tn (Priest) on Mar 27, 2005 at 21:49 UTC
    my $data = { 'one', 'value' }; $data{'one'} # my usual logical err >:< $data->{'one'} # better :)


Re: Stupid mistakes I repeatedly make
by ambs (Pilgrim) on Mar 27, 2005 at 21:52 UTC
    Can I suggest a section on TPR with these mistakes?

    Alberto Simões

      I've actually considered a "Stupid Code" thing that would take up a quarter of a page in each issue, and maybe I could even have more on the website. :)

      --
      brian d foy <brian@stonehenge.com>
Re: Stupid mistakes I repeatedly make
by graff (Chancellor) on Mar 27, 2005 at 23:03 UTC
    I haven't actually done this one yet, but I have seen others do it, and like yawning, it almost seems contageous at times (I've caught myself on the verge of doing it):
    my $some_scalar, @some_array, %some_hash, $and_so_on;
    It's the kind of habit that makes people want to just comment out the "use strict" line, or delete it entirely, before they get accustomed to it.
Re: Stupid mistakes I repeatedly make
by jhourcle (Prior) on Mar 28, 2005 at 02:31 UTC
    I make way too many typos when writing code, and I'll say that I tend to classify them in the following manner, in no particular order:
    • Those items completely slip through both use strict; and use warnings;. Take for instance the following:

      #@array contains an odd number of values. my %hash = ( key => @array ); # when you meant to say: my %hash = ( key => \@array ); # or my %hash = ( key => [@array] );

      This item includes just about any logic error, too.

    • Those items that generate useful error messages, provided you had both use strict; and use warnings; in place. (too many to list). As things go, I like these, much better than the others.

    • Those items that generate error messages, even without use strict; or use warnings. Of course, this group should never matter, as there's really no excuse for not using strict and warnings. (when you need to shut a warning off, fine, but just shut off the particular warning you need, in the limited scope that it's needed).

    • The items that throw errors, but they're either useless errors that you can't easily trace, or they point you to some line number that's functionally useless:

      Missing right curly or square bracket at line 3281.

      Okay, it's not useless, but it's something when the error message tells you something's wrong, but you have to do some real digging 'till you actually find where the problem is, and just what you've managed to do wrong. (this includes any of those error messages where it takes more than 5 minutes to track down just what went wrong).

Re: Stupid mistakes I repeatedly make
by sfink (Deacon) on Mar 28, 2005 at 05:24 UTC
    Yup, every one of those is very familiar. I go through periods where I screw up one of them constantly, then I get better and start screwing up another one.

    The one missing one from that list that I have recently picked up is

    my %h = ( name = 'Bob', age = 37, . . . );
    Never used to do that, but recently I've done it half a dozen times.
Re: Stupid mistakes I repeatedly make
by DrWhy (Chaplain) on Mar 28, 2005 at 15:19 UTC
    I rarely make any of these mistakes, although I've done the first kind of thing with chomp a bunch of times. (my @chomparr = map chomp, @rawarray; my solution to this has been, just to accept chomp in place: chomp for @array. Here are some of my favorite mistakes:

    ;
    I'm always leaving out semicolons in random places where they are required. This has gotten worse lately as I have been switching back and forth between Perl and Python alot.

    }
    As others have mentioned in this thread, leaving out a closing brace (or having an extraneous open brace) can be a pain to track down since Perl's error output on this one is not optimally helpful. I sometimes have to take a binary approach to finding the problem. Start by sticking a __END__ in about the middle of the code. If you still get this error move the __END__ to about 3/4ths of the way down. If you don't, move it up to the 1/4 position. And so on.

    use Data::Dumper warn Dumper($var);
    This is really just a variation on the ';' issue above but I do it so often it deserves its own listing.

    sub mysub($a) {my ($a) = @_; ...}
    This is another case of Python poisoning.

    if $this eq $that {do something}
    Parentheses are optional so many places that I (or at least my fingers) forget where they are required.

    use Module qw( $a, $b, $c )
    'Fortunately' this usually causes a compile error or at least a warning with -w, so I catch this quickly.

    --DrWhy

    "If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."

      I'm starting to notice something similar now that I've been doing more Javascript programming. For example, the dot-notation for objects/references is really taking over my finger memory. The lack of sigils in Javascript is messing me up, as well, when I return to the Mothership.

      I notice it again when moving back and forth between gvim and textareas in browsers. 0wc newtext[ESC] doesn't seem to work in Firefox ...

      Being right, does not endow the right to be rude; politeness costs nothing.
      Being unknowing, is not the same as being stupid.
      Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
      Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

        When it comes to sigils I'm doing the oposite. I keep using them in my JavaScript and VB. And often even adding ; at the end of lines of the VB code.

        Maybe it's because I spend most time with Perl and MS SQL, both using sigils for their variables.

        Jenda
        We'd like to help you learn to help yourself
        Look around you, all you see are sympathetic eyes
        Stroll around the grounds until you feel at home
           -- P. Simon in Mrs. Robinson

Re: Stupid mistakes I repeatedly make
by Roy Johnson (Monsignor) on Mar 28, 2005 at 16:57 UTC
    What do I really get? A list of the return values of s///, which are either 1s or empty strings.,
    You also get modifications in the original array.

    Caution: Contents may have been coded under pressure.
Re: Stupid mistakes I repeatedly make
by smalhotra (Scribe) on Mar 29, 2005 at 01:52 UTC
    The ones I find most annoying are those that are hard to debug (but you know to look for them after the first dozen times). Another one that I have fallen for a number of times is in list/hash creation calling a function/method that can return and empty list:

    my $var = { a => func(), b => $var };             ## e.g. CGI->param(), or XML::Xerces::DOMDocument->getElements
    if func() simply does a return; then the hash becomes { a => b, $var => undef } normally that will give you a 'odd-number of elements in hash assignment' warning, but do it twice in one list and you're out of luck. Sometimes I wish '=>' could force scalar context on the right operand.

    Of course the: print Dumper $var; without use Data::Dumper;. This one time I had an app that seemed to be doing everything write, except writing it's data. Some of it would be there, some would not, all the filehandles were being opened successfully. Finally after about an hour of debugging everything, and thinking the system was haunted, I changed one of the lines to $fh->print($data) or die $!. $! told me the disk was out of space. Turned out that another unrelated app was continuously forking and coreing. The cleanup app would barely free some space for me to write some data before the disk filled up again!

    $will->code for @food or $$;

Re: Stupid mistakes I repeatedly make
by Anonymous Monk on Mar 29, 2005 at 12:08 UTC
    use Devel::Size; ... quick test program ...; print total_size(\%some_datastructure); # Error, Devel::Size has useless export functionality.
    Although I'm not sure whether that's my mistake, or Devel::Size's.
Re: Stupid mistakes I repeatedly make
by doom (Deacon) on Mar 29, 2005 at 23:04 UTC
    On the subject of forgetting to use Data::Dumper;, my solution is to use some standard code templates so that I start out with a stack of standard "use" statements
    use strict; use warnings; use Carp; $|=1;
    Adding use Data::Dumper; to that list sounds like a good idea. I also have the template insert a standard pod framework (with the name of the file filled in automatically).

    I do this in emacs, with the newish package called template.el.

    And actually I run it using a emacs lisp package that I've been working on: perlnow.el. I've got separate commands for starting work on scripts, OOP modules, proceedural modules and *.t code, all of which use different templates.

Re: Stupid mistakes I repeatedly make
by guha (Priest) on Mar 30, 2005 at 20:22 UTC

    My most irritating mistake concerns the use of x, the repetition operator.

    my $multiple_Zs = 7 x 'Z'; ##Wrong
    instead of
    my $multiple_Zs = 'Z' x 7; ##Correct

    I'm not sure but I guess this has something to do with that English is not my first language. I think the natives read it as "Z times 7" and then is DWIMs. In Swedish it spoken the other way around. But all in all, this is one of only a few cases where Perl NDWIM.

      In Swedish it spoken the other way around.

      I disagree, and being swedish I can do that. :-) Maybe you think like that, but not everyone does. "Times" in swedish, "gånger", is just as commutative as "times". A hypothesis is that one may think like that because that's how one often does it when being taught algebra in school: 7a + 3b = 2c.

      If you don't look at it like multiplication but rather as "repeated ... times" it perhaps would be easier to remember.

      ihb

      See perltoc if you don't know which perldoc to read!

Re: Stupid mistakes I repeatedly make
by dragonchild (Archbishop) on Mar 30, 2005 at 20:50 UTC
    The biggest mistake I make is when I'm prototyping something, I usually forget to put
    use strict; use warnings;
    at the top. Since over half my prototypes get rm'ed, this usually isn't a problem. But, when a prototype morphs into a real project, I'm not using strict. (!!!) I once had to retrofit 20+ modules in the same project with this "fix".

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

      That's the worst.. which is why I do things like:
      use strict; use warnings; print "hello world!\n";

      IOW, even very short programs. (note that is a poor example as I'd just command line it.. but you get my point) This is the first lesson that I learned and I learned it well. The next 3 years was learning to RTFM.
Re: Stupid mistakes I repeatedly make
by g0n (Priest) on Mar 31, 2005 at 11:37 UTC
    One of my most regular stupid mistakes is typing:

    vi newpieceofcode.pl

    before trying

    www.cpan.org

    :-)

    Update 2007-10-09: Attempting to use $frame->destroy as part of the process of recomposing GUIs.

    g0n, backpropagated monk
Re: Stupid mistakes I repeatedly make
by rg0now (Chaplain) on Apr 04, 2005 at 23:02 UTC
    Hey folks! Here is a nice thread on p6l, which, along the lines of this discussion, could be titled as Stupid mistakes I repeatedly make with Perl 6!

    I just can't wait to the new challenges of making stupid mistakes with Perl 6...

    rg0now

      Well, hey, at least they'll be different stupid mistakes. I was reassured by most of the articles on this thread that Perl 6 will prevent most of the mistakes that people make in Perl 5. The only red flag I saw was how semicolons sneak into lists sometimes, so I'm thinking about how to keep that from becoming tragic in Perl 6. Currently it would turn the list into a list of lists, which is not likely to return a useful diagnostic. Probably we'll fix it by only differentiating semicolon from comma if bound to an array of Lazy lists. Otherwise we can just make it behave like a strange looking comma, which will effectively be a no-op if you accidentally type it at the end of a list.
        I am not entirely sure I get your point. You mean that if you mistype the comma in
        @array[10, 42]
        (which would be just two elements of @array similar to Perl5) and accidentally change it to a semicolon
        @array[10; 42]
        then you get a multi-dimensional array? Do arrays automatically promote to multiple dimensions? If this is the case, then it is indeed a call for stupid mistakes, which are hard to uncover...

        By the way: for me at least Perl 6 native multi-dimensional arrays do not seem to be essential. I mean they are pretty nice, but I could definitely live without them in Perl 6.0.0. At least, poor autrijus might have some less sleepless nights implementing hard-to-implement-only-marginally-useful language features...:-)

        rg0now

Re: Stupid mistakes I repeatedly make
by tlm (Prior) on Apr 30, 2005 at 14:20 UTC

    OK, I have to add one more:

    eval { frobnicate(); }; if ( @$ ) { useless(); }
    @$!&*$@!?! mumble...

    the lowliest monk

Re: Stupid mistakes I repeatedly make
by pajout (Curate) on Nov 29, 2005 at 15:01 UTC
    My favorite mistake, inherited from C:
    if ($var = 1)
      My cure for that mistake (also inherited from C):
      if (1 == $var)
Re: Stupid mistakes I repeatedly make
by martin (Pilgrim) on Feb 03, 2006 at 20:28 UTC
    Perhaps somewhat off-topic, but perl related:
    $var=whatever
    ... in a shell script.
Re: Stupid mistakes I repeatedly make
by arcnon (Monk) on Feb 12, 2006 at 17:52 UTC
    I guess I must be the worst I dont know how many times I am ripping along and type : instead of ;.
Re: Stupid mistakes I repeatedly make
by Anonymous Monk on Jun 22, 2007 at 06:35 UTC
    Oh, I must be the dumbest=) One of my common mistakes is mixing "==" with "eq" and so on (in if's).
Re: Stupid mistakes I repeatedly make (map s///r)
by toolic (Chancellor) on Jan 26, 2011 at 02:34 UTC
    s/// at the end of a map()
    Me too. And I'll probably continue to do it even after perl 5.14 is released. The new /r modifier was introduced in perl 5.13.2 perlop:
    If the /r (non-destructive) option is used then it will perform the substitution on a copy of the string and return the copy whether or not a substitution occurred. The original string will always remain unchanged in this case. The copy will always be a plain string, even If the input is an object or a tied variable.
    @foo = map { s/this/that/r } @bar # /r is very useful in maps
Re: Stupid mistakes I repeatedly make
by Ralesk (Pilgrim) on Jul 24, 2013 at 23:18 UTC

    I do the semicolon-in-hashes thing a lot, but my favourite is:

    sub blah { my ($this, $that, $stuff); ## Wondering for a long time why the heck the vars are empty... }

Log In?
Username:
Password:

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

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

    My preferred Perl binaries come from:














    Results (171 votes), past polls