in reply to How's your Perl?

# 1 my @x = ( \$_, \$_ ); # 2 sub foo { print "Agree :-)\n" } {foo;redo} # 4 dump()

The closure bug/feature Unusual Closure Behaviour

# 5 sub foo { my $x if 0; ++$x; }




Replies are listed 'Best First'.
Re: Re: How's your Perl?
by davido (Cardinal) on Oct 27, 2003 at 04:04 UTC
    Though I'm almost certain that's what the OP had in mind, it relies on a bug rather than a documented feaure. For that reason I happen to like this solution to question #5 of the OP's quiz:


    Updated version that creates only one $x:

    sub { my $x; $x = \$x; }

    The anonymous sub is created and immediately falls out of existance because it's not passed to a scalar variable. And yet $x never disappears because its reference count is always going to be 1; it refers to itself.

    It probably doesn't qualify as a static, and is pretty much useless, but it meets the definition of static that the OP gave.


    "If I had my life to live over again, I'd be a plumber." -- Albert Einstein
      oops, you're right, my definition of "static" in the clarification was flawed :-)

      I do mean function-scoped static like in C/C++ ofcourse

      btw tachyon, your #1 solution isn't:
      perl -le 'my @x = ( \$_, \$_ ); $x[0]=42; print $x[1]'

        Read your rules. You don't specify HOW the value of $x[0] is changed :-) vis Create an array @x such that changing $x[0] also sets $x[1] to the same value While assignment is one way to change a value....

        @x=(\$_,\$_); $_=10; print "\$x[$_] = ${$x[$_]}\n" for 0..$#x; $_=20; print "\$x[$_] = ${$x[$_]}\n" for 0..$#x; __DATA__ $x[0] = 10 $x[1] = 10 $x[0] = 20 $x[1] = 20

        cheers $[



      I do not think your code does what you think it does. You have two different $x variables shown in your anonymous subroutine, not a single one referencing itself.
      A static variable in a subroutine context would be created only once and hold its value between invocations. You've created a circular reference in an uninvokable routine. Even if it weren't optimized away, of which I am uncertain, it bears no resemblance to a static variable.
        You are correct, given the conventional definition of a static variable. But the Original Poster provided us with a test of expert Perl prowess, and went so far as to give us his expert definition of static:

        "static variable" means a variable with infinite lifetime...

        My solution meets his spec. In a rediculous way, of course... but then again it's a rediculous quiz.


        "If I had my life to live over again, I'd be a plumber." -- Albert Einstein
Re: Re: How's your Perl?
by Juerd (Abbot) on Oct 27, 2003 at 06:40 UTC

    my @x = ( \$_, \$_ );

    No, that's not good enough :)

    my @x = ( \$_, \$_ ); $x[0] = 5; $x[1] == 5 or die;

    Juerd # { site => '', plp_site => '', do_not_use => 'spamtrap' }