I am having a problem returning data from a sub. I declare an array while calling a sub at the same time so it will return the data. It works unless I need to do a for loop.
Please review the code:
use strict;
use warnings;
my $test = 'DATA';
my @test_1_data = test_1($test);
my @test_2_data = test_2($test);
sub test_1{
read( DATA, my $foo1, 0x04 );
read( DATA, my $foo2, 0x04 );
read( DATA, my $foo3, 0x04 );
read( DATA, my $foo4, 0x04 );
return ( $foo1, $foo2, $foo3, $foo4 );
}
sub test_2{
for(0 .. 3){
read( DATA, my $foo1, 0x04 );
read( DATA, my $foo2, 0x04 );
read( DATA, my $foo3, 0x04 );
read( DATA, my $foo4, 0x04 );
return ( $foo1, $foo2, $foo3, $foo4 ); #should return "belo
+ngs to sub_2" 4 times
} #for a total of 0
+x10 in length each loop
}
print ( "\nsub test_1:\n" );
print $_ for(@test_1_data), "\n\n";
print "sub test_2:\n";
print $_ for(@test_2_data), "\n"; #should print "belongs to sub_2" 4 t
+imes on the same line.
__DATA__
belongs to sub_1belongs to sub_2belongs to sub_2belongs to sub_2belong
+s to sub_2
Any help would be very much appreciated :)
EDIT: Solution below, return will exit the loop.
sub test_2{
my @array;
for(0 .. 3){
read( DATA, my $foo1, 0x04 );
read( DATA, my $foo2, 0x04 );
read( DATA, my $foo3, 0x04 );
read( DATA, my $foo4, 0x04 );
push (@array, ($foo1, $foo2, $foo3, $foo4 )); #push to arr
+ay while inside of for loop
}
return (@array); #return it after all loop iterations are complete
}
Thanks everyone :)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.