CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



Wildcard
Novice

Oct 1, 2017, 10:59 AM

Post #1 of 4 (1518 views)
why doesn't the return function work here? Can't Post

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

Post #2 of 4 (1516 views)
Re: [Wildcard] why doesn't the return function work here? [In reply to] Can't Post

$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

Post #3 of 4 (1509 views)
Re: [Wildcard] why doesn't the return function work here? [In reply to] Can't Post


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

Post #4 of 4 (1469 views)
Re: [Laurent_R] why doesn't the return function work here? [In reply to] Can't Post

THanks a ton! I completely missed on that one Blush

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives