Question

I am trying to create the subroutine mypush with similar functionality of inbuilt push function, but the below code is not working properly.

    @planets = ('mercury', 'venus', 'earth', 'mars');
    myPush(@planets,"Test");

    sub myPush (\@@) {
         my $ref = shift;
         my @bal = @_;
         print "\@bal :  @bal\nRef : @{$ref}\n";
         #...
    } 
Was it helpful?

Solution

At this line:

    myPush(@planets,"Test");

Perl hasn't yet seen the prototype, so it can't apply it. (If you turn on warnings, which you always should, you'll get a message that main::myPush() called too early to check prototype.)

You can either create your subroutine before you use it:

    sub myPush (\@@) {
         my $ref = shift;
         my @bal = @_;
         print "\@bal :  @bal\nRef : @{$ref}\n";
         #...
    }

    @planets = ('mercury', 'venus', 'earth', 'mars');
    myPush(@planets,"Test");

or else at least pre-declare it with its prototype:

    sub myPush (\@@);

    @planets = ('mercury', 'venus', 'earth', 'mars');
    myPush(@planets,"Test");

    sub myPush (\@@) {
         my $ref = shift;
         my @bal = @_;
         print "\@bal :  @bal\nRef : @{$ref}\n";
         #...
    }

OTHER TIPS

If you are sure of the functions and their names, you can just put an ampersand before the call:

@planets = ('mercury', 'venus', 'earth', 'mars');
&myPush(@planets,"Test");

sub myPush (\@@) {
     my $ref = shift;
     my @bal = @_;
     print "\@bal :  @bal\nRef : @{$ref}\n";
     #...
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top