in reply to Re^3: %hash (@array && use constant) in Modules
in thread %hash (@array && use constant) in Modules
When the person above you said 'inline', I don't think he was referring to Inline::C or anything like that. Rather, that the Perl compiler knows to optimize "constant" subroutines at compile-time and replace its subroutine/stack-calling stuff with... well, constant values
As an example, I created a program around the "Foo" package example we're using here, and I expanded the "Foo" package as well. Here it is:
#!/usr/bin/perl -w
use strict;
my $foo = Foo->new();
$foo->setBar('10');
print "\$foo's 'bar' value is = " . $foo->getBar() . "\n";
exit 0;
package Foo;
use constant BAR => 1;
use constant BAZ => 2;
use constant SO_ON => 3;
use constant SO_FORTH => 4;
sub new {
return bless ([], +shift);
}
sub getBar {
my $self = shift;
$self->BAR;
}
sub setBar {
my $self = shift;
$self->BAR = +shift;
}
Now, look at what this looks like when I run it through B::Deparse
rdice@tanru:~$ perl -MO=Deparse,-uFoo constants.pl
my $foo = 'Foo'->new;
$foo->setBar('10');
print q($foo's 'bar' value is = ) . $foo->getBar . "\n";
exit 0;
sub Foo::BAR () {
package constant;
$scalar;
}
sub Foo::BAZ () {
package constant;
$scalar;
}
sub Foo::SO_ON () {
package constant;
$scalar;
}
sub Foo::SO_FORTH () {
package constant;
$scalar;
}
sub Foo::new {
package Foo;
return bless([], shift @_);
}
sub Foo::getBar {
package Foo;
my $self = shift @_;
$$self1;
}
sub Foo::setBar {
package Foo;
my $self = shift @_;
$$self1 = shift @_;
}
constants.pl syntax OK
This is a reflection of how Perl sees this program after compilation and optimization. Notice that there is NO subroutine call within sub Foo::getBar or sub Foo::setBar with regards to the BAR 'constant', which is really a subroutine, but has been optimized back to being a constant -- namely, "1".
Cheers,
Richard
|
|---|