Home: Perl Programming Help: Intermediate:
why doesn't the return function work here?



Wildcard
Novice

Oct 1, 2017, 10:59 AM


Views: 4911
why doesn't the return function work here?

Hello there :)

I experimented a bit with the return function, and I can't seem to find a way to make it properly work. I tried 2 codes:


Code
use strict;  
use warnings;



my (@einsref, @zweiref) = tutnix();

print "1: ", join (",", @einsref), "\n";
print "2: ", join (",", @zweiref), "\n";

sub tutnix

{
my @eins = (1..10);
my @zwei = (11..15);


return (@eins, @zwei);

}


it gives the numbers from 1 to 15, but it should 1 to 10 and 11 to 15.

Code 2, which I think is the proper one, but works somehow even less than the first one:


Code
my ($einsref, $zweiref) = tutnix();  

print "1: ", join (",",@einsref), "\n";
print "2: ", join (",",@zweiref), "\n";

sub tutnix

{
my @eins = (1..10);
my @zwei = (11..15);


return (\@eins, \@zwei);

}


I just can't figure out what went wrong :( PErhaps the compiler can not handle the closure veriables.


FishMonger
Veteran / Moderator

Oct 1, 2017, 2:22 PM


Views: 4909
Re: [Wildcard] why doesn't the return function work here?

$einsref and @einsref are 2 entirely separate vars.

$einsref is a reference to an array and needs to be de-referenced.


Code
my ($einsref, $zweiref) = tutnix();   

print "1: ", join (",",@{$einsref}), "\n"; # the braces are optional
print "2: ", join (",",@{$zweiref}), "\n";

sub tutnix
{
my @eins = (1..10);
my @zwei = (11..15);

return (\@eins, \@zwei);

}



(This post was edited by FishMonger on Oct 1, 2017, 2:24 PM)


Laurent_R
Veteran / Moderator

Oct 1, 2017, 11:17 PM


Views: 4902
Re: [Wildcard] why doesn't the return function work here?


Quote
it gives the numbers from 1 to 15, but it should 1 to 10 and 11 to 15.

No because the two arrays returned by the subroutine are "flattened" into a single list which is then slurped into the @einsref array.

The right way to prevent this is to use array ref, as you tried to do in your second code, and which will work with FishMonger's correction.


Wildcard
Novice

Oct 9, 2017, 10:30 AM


Views: 4862
Re: [Laurent_R] why doesn't the return function work here?

THanks a ton! I completely missed on that one Blush