develooper Front page | perl.fwp | Postings from July 2003

Re: my if?

From:
fun_with_perl
Date:
July 2, 2003 04:20
Subject:
Re: my if?
Message ID:
bduf34$nke$1@post.home.lunix
In article <3F027BE8.995.CC857CE8@localhost>,
	"Bernie Cosell" <bernie@fantasyfarm.com> writes:
>> I can't think of a single Perl construct that does only one thing,
>> and that can be done with about the same number of keystrokes
>> by a more general construct.
>
> How about "our"?
>

"our" is more than just a use vars replacement, even if that is a
popular use. "our" makes a lexical scoped alias of a global. There 
is no other way to get the effect that I know.

perl -le '
package main; 
our $a; 
package foo; 
$a=5; 
print "foo: $foo::a"; 
print "main: $main::a"
'

foo: 
main: 5

And in response to some elses argument, just because perl can have
multiple ways to express one thing does in no way imply that you
must have multiple ways to express one thing in order to be perlish.

The "alternate form" usually exists if there is a common use where the
plain form is awkward.

"static" variabls are definitely not common, and personally I don't
consider the lexical notation awkward. I actually consider it clearer
since it clearly shows the variable value has a longer lifetime than
the function activation. I always considered C function scope static 
variables extremely awkward even before I knew perl. The case with an 
initializer is especially ugly since it's an action that looks like it's 
done every time a function is executed, but is done only once actually.

You would for example have to explain to people why you can't do this:

sub foo {
    ....
    my $a = ...;
    ....
    static $b = $a+3;
    ...
}

(comparable to that other favorite, named functions within named functions)

And what would be the moment the initializer is executed in perl anyways ?
compile time (implied BEGIN) ? Run-time (so there is code that runs in
at a time you would normally not expect. Function bodies normally have no
runtime effect) ? First use of the function (so the effect of the 
intializer depends on action at a distance, the exact moment the first 
call gets done) ?

The lexical scope solution is again very clear here. It uses the moment
runtime passes there, this time not unexpectedly hidden inside a body.



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About