Re: Subroutines with &
- From: Sherm Pendley <sherm@xxxxxxxxxxx>
- Date: Wed, 05 Oct 2005 02:25:11 -0400
Bertilo Wennergren <bertilow@xxxxxxxxx> writes:
> But I don't understand why I only sometimes get an actual error when I call
> such a badly declarated with an argument. It probably has something to do
> with my always putting all the subroutines at the end of the code, but I
> still can't make the whole puzzle fit.
That's exactly it. The compiler starts at the top of your code and compiles
to the end, so when it gets to a function call it's only aware of whatever
prototypes have been declared above the call. But that's just a warning, not
an error. It can still call the function, it just can't verify that the number
and type of arguments are correct.
For example, take this script:
#!/usr/bin/perl
use warnings;
use strict;
# foo() has not been prototyped at this point, so arguments aren't checked
print foo();
# Oops, foo() has a prototype now - but it's too late to go back and check
# that earlier call to foo().
sub foo() {
return "Howdy\n";
}
In addition to the expected "Howdy", it produces the following warning:
test.pl:6: main::foo() called too early to check prototype
You'll get a much more thorough description of the problem, and suggested
solutions, if you do "use diagnostics" instead of "use warnings".
There are two ways to deal with that. You could declare the sub above the
rest of the code. Or, you could forward declare the sub, like this:
#!/usr/bin/perl
use warnings;
use strict;
# Forward declare the subroutine foo() - define it later
sub foo();
print foo();
sub foo() {
return "Howdy\n";
}
If you've done any C/C++ programming, you'll feel right at home with this
declaration/definition split. If you've only done Java before this, you'll
find it bizarre beyond words. ;-)
sherm--
--
Cocoa programming in Perl: http://camelbones.sourceforge.net
Hire me! My resume: http://www.dot-app.org
.
- Follow-Ups:
- Re: Subroutines with &
- From: Bertilo Wennergren
- Re: Subroutines with &
- References:
- returning references, etc.
- From: Dave
- Re: returning references, etc.
- From: Paul Lalli
- Subroutines with & (was: Re: returning references, etc.)
- From: Bertilo Wennergren
- Re: Subroutines with & (was: Re: returning references, etc.)
- From: Tad McClellan
- Re: Subroutines with & (was: Re: returning references, etc.)
- From: Bertilo Wennergren
- Re: Subroutines with &
- From: Sherm Pendley
- Re: Subroutines with &
- From: Bertilo Wennergren
- returning references, etc.
- Prev by Date: Re: FAQ 9.17 How do I check a valid mail address?
- Next by Date: Re: Take over STDOUT / STDERR for Perl embedded in C application
- Previous by thread: Re: Subroutines with &
- Next by thread: Re: Subroutines with &
- Index(es):
Relevant Pages
|