
mhx
Enthusiast
Feb 24, 2002, 1:56 AM
Post #13 of 18
(11416 views)
|
Re: [freddo] Perl code (SSI) to detect day and time
[In reply to]
|
Can't Post
|
|
Yep, the subroutine needs an empty prototype to be inlined: [perl] sub BADANSWER { 41; } sub ANSWER () { 42; } printf "the answer is %d\n", BADANSWER; printf "the answer is %d\n", ANSWER; [/perl] will be turned into [perl] sub BADANSWER { 41; } sub ANSWER () { 42; } printf "the answer is %d\n", BADANSWER(); printf "the answer is %d\n", 42; [/perl] Also, if you prefix the call to the constant subroutine with an &, it is also not inlined by the optimizer. This is usually done wrong when using constant subroutines as hash keys: [perl] use constant ONE => 1; use constant TWO => 2; my %wrong = ( ONE => 'ONE', TWO => 'TWO' ); my %bad = ( &ONE => 'ONE', &TWO => 'TWO' ); my %good = ( ONE() => 'ONE', TWO() => 'TWO' ); my %also_ok = ( ONE , 'ONE', TWO , 'TWO' ); print "wrong: $good{ONE}\n"; print "bad: $good{&ONE}\n"; print "good: $good{ONE()}\n"; print "better: $good{+ONE}\n"; [/perl] This will lead to the following optimized code: [perl] sub TWO () { package constant; $scalar; } sub ONE () { package constant; $scalar; } my(%wrong) = ('ONE', 'ONE', 'TWO', 'TWO'); my(%bad) = (&ONE, 'ONE', &TWO, 'TWO'); my(%good) = (1, 'ONE', 2, 'TWO'); my(%also_ok) = (1, 'ONE', 2, 'TWO'); print "wrong: $good{'ONE'}\n"; print "bad: $good{&ONE}\n"; print "good: $good{1}\n"; print "better: $good{1}\n"; [/perl] As you can see, you cannot usually pass the hash key as a bareword, since it would be treated as a string then. When you use & to disambiguate, the optimizer won't inline your constant. It'll also pass the @_ array to the sub although it has a prototype. The 'right' way to disambiguate is to use an empty argument list or, if the context allows it, to prepend a unary plus. -- mhx
At last with an effort he spoke, and wondered to hear his own words, as if some other will was using his small voice. "I will take the Ring," he said, "though I do not know the way."-- Frodo
|