Click here to Skip to main content
15,073,911 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to return an array from a subroutine and use it another subroutine. It prints nothing when I do this.

PERL
#!/usr/bin/perl
use strict;
use warnings;

# Subroutine prototypes
sub getArray();

# Get array
sub dispArray
{
    my @one = getArray();
    print "$one[1]\n";
}
sub getArray()
{
    my @array1 = ("a", "b", "c", "d");
    return @array1;
}


But works fine when I do this i.e not calling it from another sub routine


PERL
#!/usr/bin/perl
use strict;
use warnings;

# Subroutine prototypes
sub getArray();

# Get array

my @one = getArray();
print "$one[1]\n";

sub getArray()
{
    my @array1 = ("a", "b", "c", "d");
    return @array1;
}



What is the reason behind it and how can I implement it correctly by calling getArray() from within another sub routine. Any help will be appreciated.
Posted

1 solution

Try to avoid prototypes and the following will yield the result you want every time by also checking what the caller wants.
#!/usr/bin/perl
use strict;
use warnings;

sub getArray()
{
    my @array1 = ("a", "b", "c", "d");
    return @array1 if wantarray;
    return \@array1;
}

# Get array
sub dispArray
{
    my @one = getArray();
    print "$one[1]\n";
}

Good luck!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900