Perl function prototype
I am trying to create a mypush routine with similar functionality to the built-in push function, but the code below is not working correctly.
@planets = ('mercury', 'venus', 'earth', 'mars');
myPush(@planets,"Test");
sub myPush (\@@) {
my $ref = shift;
my @bal = @_;
print "\@bal : @bal\nRef : @{$ref}\n";
#...
}
+3
source to share
2 answers
In this line:
myPush(@planets,"Test");
Perl hasn't seen a prototype yet, so it can't apply it. (If you turn on warnings, which you always should, you will get a message that main::myPush() called too early to check prototype
.)
You can either create your subroutine before using it:
sub myPush (\@@) {
my $ref = shift;
my @bal = @_;
print "\@bal : @bal\nRef : @{$ref}\n";
#...
}
@planets = ('mercury', 'venus', 'earth', 'mars');
myPush(@planets,"Test");
or at least pre-declare it as your prototype:
sub myPush (\@@);
@planets = ('mercury', 'venus', 'earth', 'mars');
myPush(@planets,"Test");
sub myPush (\@@) {
my $ref = shift;
my @bal = @_;
print "\@bal : @bal\nRef : @{$ref}\n";
#...
}
+11
source to share