Here's an error that I very nearly made recently, simplified down to the bare (and rather trivial-looking) essentials:

for($i = 0; $i < 10; $i++) { &foo(); } # foo: print the first three positive integers sub foo { for($i = 1; $i <= 3; $i++) { print $i; } print "\n"; }

Uh, not good.

The problem was coming back to Perl after spending a lot of time writing PHP code, where variables inside functions are locally scoped by default. This story has a happy ending: my long-standing habit of using strict immediately caught the error, and saved me quite a bit of debugging time.

It occurs to me that this example might be useful when you're trying to convince people, especially ex-PHP types, that strict is good.

--
:wq

Replies are listed 'Best First'.
Re: Implicit context conversion error, brain.pl line 666
by Juerd (Abbot) on Apr 02, 2002 at 18:34 UTC

    The problem was coming back to Perl after spending a lot of time writing PHP code, where variables inside functions are locally scoped by default.

    And where the only efficient loop over numbers is a C-style loop. Your example can do without variables completely:

    sub foo { for (1..3) { print; } print "\n"; } for (0..9) { foo; }
    Note that I also have put the sub at the top. If you put your sub at the bottom, _ALL_ lexicals that aren't in a block are shared by subs.

    With for modifiers instead of for control structures, you can shorten your code even more:
    sub foo { print for 1..3; print "\n"; } foo for 0..9;

    U28geW91IGNhbiBhbGwgcm90MTMgY
    W5kIHBhY2soKS4gQnV0IGRvIHlvdS
    ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
    geW91IHNlZSBpdD8gIC0tIEp1ZXJk
    

Re: Implicit context conversion error, brain.pl line 666
by drewbie (Chaplain) on Apr 03, 2002 at 14:57 UTC
    This is why you should always use strict and lexical variables (aka my $x). Using strict would have helped you realize that the variables were not lexically scoped. Plus it's just good programming practice. :-) I use strict even on my throwaway scripts these days.
        This is why you should always use strict and lexical variables (aka my $x).

      You'll notice that my habit of using strict is what caught the error in the first place. :-)

      (As for lexicals, I plead PHP brain damage.)

      Update: Given the choice, I wouldn't be using PHP, but the Powers That Pay My Salary "asked" me to.

      Far from the worst language I've ever dealt with, but IMO that's damnation by faint praise.

      --
      :wq

        I didn't see "use strict" in the snippet so I made an assumption.

        And we'll let you off w/ a warning this time. But next time we catch you fooling around with that PHP stuff we'll throw the book at you. :-)