Loginskip to content

January 31st, 2006

You have a subroutine that should set a

You have a subroutine that should set a private variable based on some condition. Not unreasonably, you might code something following this general form: sub ordinal { my $what = shift; my $res = ‘first’ if $what == 1; $res = ’second’ if $what == 2; return $res; } But you’d be wrong. If we run this through perl-lwith for(1..3){ print ordinal($_)}, we get the result: first second second Eh? Shouldn’t that last line be a warning about an undefined value? Regrettably, you’ve fallen afoul of an internal optimization in Perl[4] that keeps the storage assigned to lexical variables around after they’re gone, on the premise that they may be needed again shortly. The my statement has both a compile-time effect (declaring the variable) and a run-time effect (setting it to undef, unless the statement is qualified by a failed condition). [4] That may change in a future version. Never qualify a my statement with a condition. Note that this is not talking about putting my statements inside conditions: if ((my $tag = $element->tag) ne ‘p’) { # Code using $tag } while (my ($key, $value) = each %hash) { … } which is a very good idiom in that it concisely limits the scope of the new variable to precisely the block in which you need it. 10.6 Bringing Some Closure Understanding how lexical variables work is worth the effort. Suppose you have advanced to the stage of understanding closures give yourself a pat on the back and you decide to code a few subroutines that use a private variable that way: { my $protocol = “ftp”; # default

Hint: If you are looking for very good and affordable webspace to host and run your j2ee hosting application check Virtualwebstudio j2ee web hosting services

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>