in reply to Re: 'my' buggy...
in thread 'my' buggy...

Not true (try it). The weirdness only exists when the condition is false at compile-time -- e.g., when a constant like 0 is used.

_____________________________________________________
Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a (from-home) job
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Replies are listed 'Best First'.
Re: Re: Re: 'my' buggy...
by Elian (Parson) on Apr 30, 2002 at 16:28 UTC
    Umm.... no.
    sub foo {
        my $baz = 12 if @_;
        print "$baz\n";
        $baz++;
    }
    
    foo(1);
    foo();
    foo();
    foo();
    foo(1);
    foo();
    foo();
    foo();
    
    Produces
    12
    
    1
    2
    12
    
    1
    2
    
    You don't really think I'd not check, do you? :)
      If $baz isn't being reallocated on the second loop iteration, why does the second test print out a blank line (presumably corresponding to an undef $baz) instead of "13"?

      (When I look at the results above, it doesn't give what I'd expect whether $baz is being reallocated every time, or whether it's being reallocated only when @_ has elements in it. I don't know why...)

      Update: Thanks, whoever you are :) That makes a lot of sense.

      Alan

        The variable is only cleaned up if the initialization was done. On the first iteration it is assigned and then cleaned up. On the second it is not assigned, has nothing to pick up, and is not cleaned up. On the third the value from the second is present and not cleaned up. On the fourth it is initialized and cleaned up. etc.
        That's a good question, and one I don't have the answer to.
      As for the original post, perhaps you're testing for the wrong phenomenon.

      #!/usr/bin/perl use strict; sub foo { my($bar) = @_; print "foo: $bar\n"; ++$bar; } foo(1); foo(); foo(); foo(); foo(1); foo(); foo(); foo();

      Produces:

      foo: 1 foo: foo: foo: foo: 1 foo: foo: foo:

      So the empty @_ does reset the var, which was I think your original assertion.

      Matt

      Update: Elian is right. That's what I get for posting pre-coffee. His original point involved a conditional assignment. I suppose if there's a moral to this mini-thread it is to make your parameter assignments mandatory unless you really are intending to keep old values around. :-(

        Nope, not quite. You're missing the conditional on the my, which was the important part of my original point. (Though, granted, in this case the problem the code's exhibiting is likely due to symbolic references) Add it back in and you'll see rather different behaviour.
      Ah, in my testing, I didn't use enough empty-@_ tests.

      _____________________________________________________
      Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a (from-home) job
      s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;